由TextField onChanged回调设置后,将重置String变量的值。在Button onPressed回调中选中时。但是其他数据类型似乎还可以。
我一般对Flutter和Dart都是陌生的,所以我刚刚尝试了想到的所有荒谬解决方案,例如,使用setState(),创建用于处理它的单独函数,从上下文中剥离所有其他内容,但似乎没有任何作用。
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"); }))
],
),
);
onPressed(printing itemName)内部的print语句也应该打印textField更改的任何值,但始终打印为null。
尽管textField的值正在更改(如果有一种调试方法也有帮助,请检查print语句的调试对于回调来说是徒劳的)。
问题与testVal相同,但数量和价格都很好,因为它们是整数。
我还用DateTime测试了相同的东西,它也很好用。
最佳答案
问题是因为当键盘显示或关闭Flutter框架时,会调用小部件的build
方法,并且所有本地变量都会重新启动。
解决此问题的一种简单方法是使用StatefullWidget
并将变量定义为小部件状态。
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.
}
}
关于dart - 在Flutter中设置TextField的onChanged回调后重置字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56265437/