Reputation: 411
i'm doing a basic app but it doesn't work propertly. I have one TextField but i don't want that it was empty. I have a textController and i use errorText but it doesn't work propertly. Mi code is:
void changeDesc() { showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('New description'),
content: TextField(
controller: _textController,
decoration: InputDecoration(
hintText: "description",
errorText: descriptionIncorrect
? 'Description cannot be empty'
: null,
),
),
actions: <Widget>[
FlatButton(
child: new Text('Ok'),
onPressed: () {
setState(() {_textController.text.length == 0
? descriptionIncorrect= true
: descriptionIncorrect= false;});
if (_textController.text.length != 0) {
alert.description = _textController.text;
Navigator.of(context).pop();
}
},
),
FlatButton(
child: new Text('Cancel'),
onPressed: () {
setState(() {
_textController.text.length == 0
? descriptionIncorrect= true
: descriptionIncorrect= false;});
if (_textController.text.length == 0) {
_textController.text = alert.description;
Navigator.of(context).pop();
}
},
)
],
);
});}
When i push OK button and the textField is empty the error should appear, but doesn't appear. I have tried some things but i can't do it work as i need.
Thanks.
Upvotes: 2
Views: 1979
Reputation: 1297
You need to do two steps 1- to refresh alert Dialog you need to wrap it in StatefulBuilder
widget. 2- add auto focus to your Text Field.
here's the full code.
bool descriptionIncorrect = false;
var _textController = TextEditingController();
void changeDesc() {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text('New description'),
content: TextField(
autofocus: true,
controller: _textController,
decoration: InputDecoration(
hintText: "description",
errorText: descriptionIncorrect
? 'Description cannot be empty'
: null,
),
),
actions: <Widget>[
FlatButton(
child: new Text('Ok'),
onPressed: () {
setState(() {
_textController.text.length == 0
? descriptionIncorrect = true
: descriptionIncorrect = false;
print(_textController.text.length.toString());
print(descriptionIncorrect.toString());
});
if (_textController.text.length != 0) {
alert.description = _textController.text;
Navigator.of(context).pop();
}
},
),
FlatButton(
child: new Text('Cancel'),
onPressed: () {
setState(() {
_textController.text.length == 0
? descriptionIncorrect = true
: descriptionIncorrect = false;
});
if (_textController.text.length == 0) {
_textController.text = alert.description;
Navigator.of(context).pop();
}
},
)
],
);
},
);
});
}
Upvotes: 1