首页 > 解决方案 > 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
}}

标签: formsflutterdarttabs

解决方案


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

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


推荐阅读