【发布时间】:2019-06-10 03:06:15
【问题描述】:
我正在编辑列表中的项目的屏幕。用户点击该项目,我弹出一个新页面打开,其中包含一个 DropdownButton、一个 TextFormField 和一个保存按钮。
如果您先更改 DropdownButton 值,然后点击以聚焦于 TextFormField,则对 DropdownButton 值所做的任何更改都会重置。该值返回到您导航到此页面时设置的初始状态,而不是用户选择的值。如何保留用户在此处选择的值?
为了打开编辑页面,我从正在编辑的列表项中传递参数:
final updated = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditPage(
display: commute.display,
origin: commute.origin)));
EditPage 类本身:
class EditPage extends StatefulWidget {
String display;
String origin;
EditPage({Key key, @required this.display, @required this.origin})
: super(key: key);
@override
EditPageState createState() => EditPageState();
}
class EditPageState extends State<EditPage> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Edit"),
),
body: Form(
key: _formKey,
child: Column(
children: <Widget>[
DropdownButton(
value: widget.origin,
onChanged: (value) {
this.setState(() {
widget.origin = value;
});
},
),
TextFormField(
initialValue: widget.display,
onSaved: (value) {
setState(() {
widget.display = value;
});
},
),
RaisedButton(
child: Text('Save'),
onPressed: () {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
final thing =
Thing(display: widget.display, origin: widget.origin);
Navigator.pop(context, thing);
}
},
),
],
),
),
);
}
}
【问题讨论】:
-
我认为你需要为每个 TextFormField 设置 TextEditingController 来保存文本字段的状态
标签: flutter