Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter assign text onchange value to variable

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);
        },
like image 390
Kalev Avatar asked Sep 19 '25 11:09

Kalev


1 Answers

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;
                  });
                }),
          ],
        ),
      ),
    ));
  }
}

demo

OR You could just add setState((){}) directly inside onChanged like this

onChanged: (newText) {
    newTaskTitle = newText;
    setState((){});
  },
like image 119
Pro Avatar answered Sep 22 '25 06:09

Pro