Reputation: 2019
I have a widget with a TextField that I'm initializing from a StreamBuilder
, trying to use the bloc pattern. A Contact model is coming in through the stream. This is working to initially populate the TextField. My question is about reading the value after the user updates the TextField and then presses the Save button. How do I read the value from the TextField. I've included a simple example of what I'm trying to do.
void getTextValues() {
//???
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Contact>(
stream: bloc.getContact,
builder: (context, contact) {
return Column(
children: <Widget>[
TextField(
controller: TextEditingController(text: contact.data.name),
),
new RaisedButton(
padding: const EdgeInsets.all(8.0),
textColor: Colors.white,
color: Colors.blue,
onPressed: getTextValues,
child: new Text("Save"),
),
],
);
},
);
}
I think I could declare a TextEditingController and assign that to the controller property but I don't see a way to give that an initial value from the StreamBuilder. Am I missing something there?
TextEditingController nameController = TextEditingController();
....
controller: nameController,
Upvotes: 0
Views: 806
Reputation: 267404
To assign TextEditingController
a default value, use
TextEditingController _controller = TextEditingController(text: "Default value");
And to retrieve the value from a controller you can use
_controller.value
Upvotes: 0
Reputation: 3892
I think I could declare a TextEditingController and assign that to the controller property but I don't see a way to give that an initial value from the StreamBuilder.
There is a way. Change your builder code to this:
builder: (context, contact) {
nameController.value = TextEditingValue(text: contact.data.name);
return Column(
children: <Widget>[
TextField(
controller: nameController,
),
new RaisedButton(
padding: const EdgeInsets.all(8.0),
textColor: Colors.white,
color: Colors.blue,
onPressed: getTextValues,
child: new Text("Save"),
),
],
);
},
Upvotes: 1