如何重置(清除)flutter app中的表单字段?一旦数据提交到服务器?
在我的应用程序中,我有2页。
第1页输入表格详细信息,如姓名,地址等
第2页是上传图片。
第1页将数据推送到第2页。 (这里我没有做推更换,意味着第2页位于首页顶部)
第二页是选择图像,并将表单数据和图像上传到服务器。
我的问题是
上传完成后,如何重置所有2个页面?
我正在使用firebase服务器上传我的数据!
提前致谢
例如,使用GlobalKey<FormState>
访问表单状态和reset()
字段。考虑到这一点,您可以:
class Screen1 extends StatefulWidget {
_Screen1State createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
final _formKeyScreen1 = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First screen'),
),
body: Center(
child: Form(
key: _formKeyScreen1,
child: Column(
children: <Widget>[
TextFormField(),
TextFormField(),
TextFormField(),
RaisedButton(
child: Text('Navigate to second screen...'),
onPressed: () => Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => Screen2(_formKeyScreen1),
)),
)
],
),
),
),
);
}
}
class Screen2 extends StatefulWidget {
final GlobalKey<FormState> firstScreenFormKey;
Screen2(this.firstScreenFormKey);
_Screen2State createState() => _Screen2State();
}
class _Screen2State extends State<Screen2> {
final _formKeyScreen2 = GlobalKey<FormState>();
void _processData() {
// Process your data and upload to server
_formKeyScreen2.currentState?.reset();
widget.firstScreenFormKey?.currentState?.reset();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second screen'),
),
body: Center(
child: Form(
key: _formKeyScreen2,
child: Column(
children: <Widget>[
TextFormField(),
TextFormField(),
TextFormField(),
RaisedButton(
child: Text('Submit data'),
onPressed: () => _processData(),
)
],
),
),
),
);
}
}
class Screen1 extends StatefulWidget {
_Screen1State createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
final _formKeyScreen1 = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First screen'),
),
body: Center(
child: Form(
key: _formKeyScreen1,
child: Column(
children: <Widget>[
TextFormField(),
TextFormField(),
TextFormField(),
RaisedButton(
child: Text('Navigate to second screen...'),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(
builder: (BuildContext context) => Screen2(),
))
.then((_) => _formKeyScreen1.currentState.reset());
},
)
],
),
),
),
);
}
}
class Screen2 extends StatefulWidget {
_Screen2State createState() => _Screen2State();
}
class _Screen2State extends State<Screen2> {
final _formKeyScreen2 = GlobalKey<FormState>();
void _processData() {
// Process your data and upload to server
_formKeyScreen2.currentState?.reset();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second screen'),
),
body: Center(
child: Form(
key: _formKeyScreen2,
child: Column(
children: <Widget>[
TextFormField(),
TextFormField(),
TextFormField(),
RaisedButton(
child: Text('Submit data'),
onPressed: () => _processData(),
)
],
),
),
),
);
}
}