forms - Flutter:如何在选项卡中管理表单
问题描述
我有一个标签栏,其中包含三个标签,每个标签的形式不同。我在底部有一个保存按钮来保存所有这些。问题是,只有当相关选项卡处于活动状态时,才能访问三个表单的 globalkeys currentstate。因此,当我在选项卡 2 和 3 中时,formkey1.currentstate 为空,依此类推。请注意,我正在与提供者一起管理状态。
关于如何解决这个问题的任何线索?
这是代码的简短版本:
class Myclass extends StatelessWidget{
final _formKey1 = GlobalKey<FormState>();
final _formKey2 = GlobalKey<FormState>();
final _formKey3 = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return DefaultTabController(length: 3, child:
Scaffold(
appBar: AppBar(
bottom: TabBar(
tabs: [
Tab(text: "TAB ONE"),
Tab(text: "TAB TWO"),
Tab(text: "TAB THREE"),
],
),
),
bottomNavigationBar:
child: Row(
children: [
FlatButton(
onPressed: (){
_save(context);
},
child: Text("Save"),
),
],
)
),
body: TabBarView(children: [
Form(key: _formKey1, ...),
Form(key: _formKey2, ...),
Form(key: _formKey3, ...),
])
),);
}
void _save(BuildContext context) async {
print(_formKey1.currentState); // NULL ON TAB 2 AND 3
print(_formKey2.currentState); // NULL ON TAB 1 AND 3
print(_formKey3.currentState); // NULL ON TAB 1 AND 2
//my save procedure
}}
解决方案
AutomaticKeepAliveClientMixin
如果你想保持它们的状态,你应该使用每个 TabView 页面。您也可以使用 aKeepAliveWrapper
来包装每一页。这是代码:
class KeepAliveWrapper extends StatefulWidget {
final Widget child;
const KeepAliveWrapper({Key key, this.child}) : super(key: key);
@override
__KeepAliveWrapperState createState() => __KeepAliveWrapperState();
}
class __KeepAliveWrapperState extends State<KeepAliveWrapper>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
@override
bool get wantKeepAlive => true;
}
像这样使用它:
KeepAliveWrapper(
child: Form(
key: _formKey1,
child: Container(),
),
)
请注意,在访问每个选项卡之前,您的子页面仍未构建。
推荐阅读
- linked-list - 区块链账本存储
- android - Marshmallow 不显示“更改默认拨号应用程序”弹出窗口
- css - 将诸如 tachyons 之类的 css 工具包添加到 next.js 项目的问题
- sql - 检查表中是否已存在字段组合
- c# - 如何检测特定对象上的碰撞?
- python - 有没有办法从资源中获取 flask_restful 中的完整 url
- mysql - Mysql左外连接与右表中不是外键的列
- javascript - 在 OpenStreetMaps 上的指针(覆盖)附近手动放置信息框(覆盖)
- java - 软件导致连接中止:在SpringBoot app中调用REST WebService时recv失败
- node.js - 无法卸载 NVM 软件包