大多数应用程序都有表单(登录、注册、数据输入),需要 user input handling 和验证。Flutter 提供 Form、TextFormField、validators 和 controllers 来构建和验证表单 — 这对任何具有 user input 的应用程序都是必不可少的。
Form 和 TextFormField
final _formKey = GlobalKey<FormState>(); // a key to access the form's state
Form(
key: _formKey,
child: Column(children: [
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) { // VALIDATION logic
if (value == null || value.isEmpty) return 'Email required';
if (!value.contains('@')) return 'Invalid email';
return null; // null = valid
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) { // run all validators
// all fields valid → submit
}
},
child: Text('Submit'),
),
]),
)
