Reputation: 2979
Im new, I trying to do a onchange value while typing in text field, the value are updating the Text widget.
I tried two way, one is from onchanged , another is using TextEditingController, none of it working.
final txtController = TextEditingController();
String onchangeval = "";
TextFormField(
onChanged: (value){
onchangeval = value;
},
controller: txtController
),
Text("value_1 : " + onchangeval),
Text("value_2 : " + txtController.text),
NOTE : currently using extends HookWidget
Upvotes: 1
Views: 4980
Reputation: 1268
You need to call setState
() which tells the framework that the widget’s state has changed and that the widget should be redrawn.
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final txtController = TextEditingController();
String onchangeval = "";
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
onChanged: (value) {
setState(() {
onchangeval = value;
});
},
controller: txtController),
Text("value_1 : " + onchangeval),
Text("value_2 : " + txtController.text),
],
);
}
}
Upvotes: 4
Reputation: 4894
You should use setState()
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final txtController = TextEditingController();
String onchangeval = "";
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
onChanged: (value) {
setState(() {
onchangeval = value;
});
},
controller: txtController),
Text(
onchangeval,
),
],
),
),
);
}
}
Refer: https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html
Upvotes: 2
Reputation: 2714
You have to put it in setstate
.
documentation: https://api.flutter.dev/flutter/widgets/State/setState.html
For making setstate
working you have to change your widget type to a StatefulWidget
final txtController = TextEditingController();
String onchangeval = "";
TextFormField(
onChanged: (value){
setState(() {
onchangeval = value;
});
},
controller: txtController
),
Text("value_1 : " + onchangeval),
Text("value_2 : " + txtController.text),
Every time you want to make visual changes in your app you will have to work with states which can change.
Upvotes: 2