gpt4 book ai didi

forms - Flutter:如何在选项卡中管理表单

转载 作者:行者123 更新时间:2023-12-05 06:05:34 26 4
gpt4 key购买 nike

我有一个标签栏,其中包含三个标签,每个标签都有不同的形式。我在底部有一个保存按钮来保存所有这些。问题是,只有当相关选项卡处于事件状态时,三种形式的全局键当前状态才能访问。因此,当我在选项卡 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
}}

最佳答案

如果您想保持每个 TabView 页面的状态,您应该使用 AutomaticKeepAliveClientMixin。您也可以使用 KeepAliveWrapper 来包装每个页面。这是代码:

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(),
),
)

请注意,在访问每个选项卡之前,您的子页面仍未构建。

关于forms - Flutter:如何在选项卡中管理表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65977424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com