Reputation: 411
I have a page with has a Text which should show the text that I introduce in a TextEditingController
. I paste only the important code, if needed more tell me please:
@override
Widget build(BuildContext context) {
return WillPopScope(
child: Scaffold(
key: _scaffoldKey,
appBar: _buildBar(context),
body: Container(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10),
),
buildTitle(),
],
)))),
onWillPop: () => _onWillPop(context));
...
}
The method buildTitle() is:
Widget buildTitle() {
return Column(children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
name == null ? "" : name,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
IconButton(
icon: Icon(Icons.edit),
onPressed: () {
changeName();
},
),
],
),
...
]);
}
And changeName() is:
void changeName() {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(builder: (context, setState) {
return AlertDialog(
title: Text('Name'),
content: TextField(
autofocus: true,
controller: _textController,
decoration: InputDecoration(
hintText: "Name of product",
errorText: incorrectName
? 'The name could not be empty'
: null,
),
),
actions: <Widget>[
FlatButton(
child: new Text('OK'),
onPressed: () {
if (_textController.text.length == 0) {
setState(() {
_textController.text.length == 0
? incorrectName = true
: incorrectName = false;
});
} else {
setState(() {
incorrectName = false;
name = _textController.text;
});
Navigator.of(context).pop();
}
},
),
FlatButton(
child: new Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
});
}
At first, name is empty so only appears the edit button, but when I click on Ok the Text doesn`t change but I have anothers methods with SetState that when I click then the name appears.
Why isn't the name updated with SetState in this case?
Upvotes: 0
Views: 6461
Reputation: 1044
Change the changeName()
return type:
Future<String> changeName() {
showDialog<String>(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Name'),
content: TextField(
autofocus: true,
controller: _textController,
decoration: InputDecoration(
hintText: "Name of product",
errorText: incorrectName
? 'The name could not be empty'
: null,
),
),
actions: <Widget>[
FlatButton(
child: new Text('OK'),
onPressed: () {
if (_textController.text.length == 0) {
Navigator.of(context).pop(null);
} else {
Navigator.of(context).pop(_textController.text);
}
},
),
FlatButton(
child: new Text('Cancel'),
onPressed: () {
Navigator.of(context).pop(null);
},
)
],
);
});
}
in Your buildTitle()
:
Widget buildTitle() {
return Column(children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
name == null ? "" : name,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
IconButton(
icon: Icon(Icons.edit),
onPressed: () async {
name = await changeName();
setState((){});
},
),
],
),
...
]);
Upvotes: 1