如何在Flutter应用中重置(清除)表单字段?数据提交到服务器后?
在我的应用中,我有2页。
第一页输入表单详细信息,例如姓名,地址等
第二页是要上传图片。
第一页将数据推送到第二页。 (这里我没有进行推送替换,这意味着第二页位于第一页的顶部)
第二页用于选择图像,并将表单数据和图像上传到服务器。
我的问题是
上传完成后如何重设全部两个页面?
我正在使用 firebase 服务器上传我的数据!
谢谢,谢谢
答案 0 :(得分:3)
例如,使用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(),
)
],
),
),
),
);
}
}