美文网首页
Flutter-Form(表单)和 SnackBar(提示)

Flutter-Form(表单)和 SnackBar(提示)

作者: 梦幽辰 | 来源:发表于2020-01-01 17:09 被阅读0次

    我们可以使用flutter自带的Form组件完成表单的创建

    class RegisterForm extends StatefulWidget {
      @override
      _RegisterFormState createState() => _RegisterFormState();
    }
    
    class _RegisterFormState extends State<RegisterForm> {
      final registerFormKey = GlobalKey<FormState>();
      String username, password;
    
      void submitRegisterForm(){
        if(registerFormKey.currentState.validate()){
          registerFormKey.currentState.save();
    
          debugPrint('username: $username');
          debugPrint('username: $password');
        }
        
      }
    
      String validateUsername(value){
        if(value.isEmpty){
          return 'Username is required.';
        }
    
        return null; 
      }
    
      String validatePassword(value){
        if(value.isEmpty){
          return 'Password is required.';
        }
    
        return null; 
      }
    
      @override
      Widget build(BuildContext context) {
        return Form(
          autovalidate: true, // 该属性为true,则开启自动校验
          key: registerFormKey, // 设置globalKey,用于后面获取FormState
          child: Column(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Username',
                  helperText: '',
                ),
                onSaved: (value){
                  username = value;
                },
                validator: validateUsername,
              ),
              TextFormField(
                obscureText: true, // 输入为密码
                decoration: InputDecoration(
                  labelText: 'Password',
                  helperText: '',
                ),
                onSaved: (value){
                  password = value;
                },
                validator: validatePassword,
              ),
              SizedBox(height: 32,),
              Container(
                width: double.infinity,
                child: RaisedButton(
                  color: Theme.of(context).accentColor,
                  child: Text('Register', style: TextStyle(color: Colors.white),),
                  elevation: 0,
                  onPressed: submitRegisterForm,
                ),
              )
            ],
          ),
        );
      }
    }
    
    预览

    SnackBar(提示)

    if (registerFormKey.currentState.validate()) {
      registerFormKey.currentState.save();
    
      debugPrint('username: $username');
      debugPrint('username: $password');
    
      Scaffold.of(context).showSnackBar(
        SnackBar(
          content: Text('Registering...'),
        )
      );
    }
    
    预览

    相关文章

      网友评论

          本文标题:Flutter-Form(表单)和 SnackBar(提示)

          本文链接:https://www.haomeiwen.com/subject/grhgoctx.html