简体   繁体   中英

String being reset after the being set in onChanged callback of TextField in Flutter

The value of the String variable is being reset after being set by the TextField onChanged callback. When checked in Button onPressed callback. But other data types seem to be fine.

I am new to Flutter and Dart in general so I have just tried all the absurd solutions that came to mind, like, using setState(), creating separate functions for handling it, stripping everything else from the context but none seem to be working.

String itemName;
String testVal;
int quantity;
int price;
return Scaffold(
  appBar: AppBar(title: Text("New Item")),
  body: Column(
    children: <Widget>[
      Text("Name"), 
      TextField(onChanged: (val) => itemName = val),
      Text("Test"), 
      TextField(keyboardType: TextInputType.text, onChanged: (val) => testVal = val),
      Text("Quantity"), 
      TextField(keyboardType: TextInputType.number, onChanged: (String val) => quantity = num.tryParse(val)),
      Row(children: <Widget>[Text("Price"), Flexible(child: TextField(maxLines: 1,keyboardType: TextInputType.number, onChanged: (String val) => price = num.tryParse(val)))]),
      Center(child: RaisedButton(child: Text("Submit"), onPressed: () { print("This is NOT working? $itemName"); }))
    ],
  ),
);

The print statement inside onPressed(printing itemName) should print whatever value the textField was changed too but it always prints null. Although the value of textField is being changed(checked that with print statements debugging is pretty futile for callbacks if there is a way to debug it that would also help).

The problem is the same with the testVal but both Quantity and Price are fine as they are ints.

I also tested the same with DateTime and it worked fine as well.

The problem is because when the keyboard is showing or closing the flutter framework calls build method of your widget and your local variables are all restarted.

One simple approach to solve this is make use of StatefullWidget and define your variables as widget state.

class YourWidget extend StatefullWidget {
   _YourWidgetState createState() => _YourWidgetState();
}

class _YourWidgetState extends State<YourWidget> {
    String itemName;
    String testVal;
    int quantity;
    int price;

     Widget build(BuildContext context) {
        return ... // return your layout.
     }
 }

I'm not sure but maybe the problem is the way you implement onChanged function. Your code is:

onChanged: (val) => testVal = val

This is the shorthand for

onChanged: (val) { return testVal = val; } // I think this is wrong

So try to change to

onChanged: (val) { testVal = val; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM