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

2020-01-01  本文已影响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...'),
    )
  );
}
预览
上一篇下一篇

猜你喜欢

热点阅读