【问题标题】:Flutter: how to manage forms in tabsFlutter:如何在选项卡中管理表单
【发布时间】:2021-01-31 09:14:00
【问题描述】:

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

【问题讨论】:

  • 我尝试将 Myclass 切换为有状态的小部件,但我得到了更好的结果,但很奇怪而且仍然不正确,例如:如果我在 tab1 上保存,我只会得到第二种形式 currentState=null。如果我在 tab2 上保存,我只会得到第一个表单 currentState=null。如果我在 tab3 上保存,我会得到第一种和第二种形式 currentState=null.
  • 我可以在颤振检查器中看到每个表单小部件仅在相关选项卡处于活动状态时才存在于小部件树中。所以 currentState 是 null 因为引用了一个不存在的小部件......

标签: forms flutter dart tabs


【解决方案1】:

如果你想保持它们的状态,你应该为每个 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(),
        ),
      )

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

【讨论】:

    【解决方案2】:

    您可以导航到包含表单的新页面(新类)。对于这 3 个表单,您可以创建 3 个类,并在选项卡栏上导航到这 3 个类。在一个类中,您可以很好地处理您的表单。观点没有区别!试试吧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      相关资源
      最近更新 更多