How to update value for TextField using StreamBuilder?
OK so i finally found the solution to my problem.
Following is my code, I have just used SharedPreferences
instead of sqflite
for the below example.Same thing can be done with sqflite
class _MyHomePageState extends State<MyHomePage> {
MyBloc myBloc = MyBloc();
TextEditingController myController = TextEditingController();
@override
void dispose() {
myBloc?.close();
myController?.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
AppPreferences.setString("data", "this is my data");
AppPreferences.getString("data").then((value){
myBloc.dataChanged(value);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder(
stream: myBloc.data,
builder: (context,snapshot){
debugPrint(snapshot.data);
myController.value = myController.value.copyWith(text: myBloc.dataValue);
return TextFormField(
controller: myController,
onChanged: (value){
myBloc.dataChanged(value);
},
);
},
),
),
);
}
}
Try the following approach:
StreamBuilder<String>(
stream: patientHealthFormBloc.doctorName,
builder: (context, snapshot) {
String doctorName = patientHealthFormBloc.doctorNameValue;
if(snapshot.hasData){
doctorName = snapshot.data/*(your name string from the stream)*/;
}
return TextFormField(
initialValue: doctorName,
onChanged: (value) {
patientHealthFormBloc.doctorNameChanged(value);
},
...
What was suggesting in my comments was something like this:
TextEditingController _textEditingController = TextEditingController();
@override
void initState() {
patientHealthFormBloc.doctorName.listen((snapshot){
setState((){
_textEditingController.text = snapshot;
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
TextFormField(
controller: _textEditingController,
onChanged: (value) {
patientHealthFormBloc.doctorNameChanged(value);
},
],
),
);
}
I didn't want to write this answer without understanding why you didn't want to use a TextEditingController or a setState. But this should achieve what you want while using the Bloc pattern.