I'm following a flutter tutorial and came across a problem. It is supposed to take a value from textfield onChanged function and assign it to a variable. However it is not working. Since it is shown on iphone, I thought perhaps it works a little different on android.
@override
Widget build(BuildContext context) {
String newTaskTitle;
return Container(
color: Color(0xff757575),
....
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
print(newTaskTitle);
},
Kalev, try using StatefulWidget
and refreshing state when you want the new text as shown below,
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
String text = 'Original text';
String newTaskTitle;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(text),
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
setState(() {
text = newTaskTitle;
});
}),
],
),
),
));
}
}
OR You could just add setState((){}) directly inside onChanged like this
onChanged: (newText) {
newTaskTitle = newText;
setState((){});
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With