I am using provider
to show if there is an error in textfield
.
if the text in textfield
is empty then it shows 'error'
as errorText
else it will show nothing,
Here’s my code:
class TextFieldPage extends StatelessWidget {
const TextFieldPage({super.key});
@override
Widget build(BuildContext context) {
final provider = Provider.of<TextFieldProvider__>(context);
TextEditingController _controller = TextEditingController();
return Scaffold(
body: Column(children: [
Consumer<TextFieldProvider__>(
builder: (context, value, child) {
return TextField(
controller: _controller,
decoration: InputDecoration(errorText: value.errorText),
);
},
),
ElevatedButton(
onPressed: () {
if (_controller.text == "") {
provider.changeErrorText('error');
} else {
provider.changeErrorText('');
}
},
child: Text("press"))
]));
}
}
class TextFieldProvider__ extends ChangeNotifier {
String _errorText = '';
String get errorText => _errorText;
changeErrorText(String text) {
_errorText = text;
notifyListeners();
}
}
The problem is when I click the button it calls ChangeErrorText()
and removes the text in TextField.
How do I avoid it?
3
Answers
The problem was that I forgot to set
listen: false
while creating an instance of provider.It should be:
Not This:
this was rebuilding the widget and text in TextField was been cleared.
replace your
_controller
Your
EditFieldPage
should be asStatefulWidget
and_controller
should be as property of_TextFieldPageState