美文网首页
13. 保存和获取表单数据

13. 保存和获取表单数据

作者: 凯司机 | 来源:发表于2020-06-08 17:35 被阅读0次

有了表单后,我们需要在点击注册时,可以同时获取和保存表单中的数据,怎么可以做到呢?

1、需要监听注册按钮的点击,在之前我们已经监听的onPressed传入的回调中来做即可。(当然,如果嵌套太多,我们待会儿可以将它抽取到一个单独的方法中)

2、监听到按钮点击时,同时获取用户名和密码的表单信息。

如何同时获取用户名和密码的表单信息?

如果我们调用Form的State对象的save方法,就会调用Form中放入的TextFormField的onSave回调

TextFormField(

  decoration: InputDecoration(

    icon: Icon(Icons.people),

    labelText: "用户名或手机号"

  ),

  onSaved: (value) {

    print("用户名:$value");

  },

),

但是,我们有没有办法可以在点击按钮时,拿到 Form对象 来调用它的save方法呢?

知识点:在Flutter如何可以获取一个通过一个引用获取一个StatefulWidget的State对象呢?

答案:通过绑定一个GlobalKey即可。

具体代码的事例:

classFormDemoextendsStatefulWidget{

  @override

  _FormDemoState createState() => _FormDemoState();

}

class_FormDemoStateextendsState{

  final registerFormKey = GlobalKey<FormState>();

  String username, password;

  void registerForm() {

    registerFormKey.currentState.save();

    print("username:$usernamepassword:$password");

  }

  @override

  Widget build(BuildContext context) {

    return Form(

      key: registerFormKey,

      child: Column(

        mainAxisAlignment: MainAxisAlignment.center,

        children: <Widget>[

          TextFormField(

            decoration: InputDecoration(

              icon: Icon(Icons.people),

              labelText: "用户名或手机号"

            ),

            onSaved: (value) {

              this.username = value;

            },

          ),

          TextFormField(

            obscureText: true,

            decoration: InputDecoration(

              icon: Icon(Icons.lock),

              labelText: "密码"

            ),

            onSaved: (value) {

              this.password = value;

            },

          ),

          SizedBox(height: 16,),

          Container(

            width: double.infinity,

            height: 44,

            child: RaisedButton(

              color: Colors.lightGreen,

              child: Text("注 册", style: TextStyle(fontSize: 20, color: Colors.white),),

              onPressed: registerForm,

            ),

          )

        ],

      ),

    );

  }

}

相关文章