Form表单
2022-07-04 本文已影响0人
乐狐
From 表单.png
//导入Material UI 组件库
import 'package:flutter/material.dart';
//程序入口
void main() {
runApp(const MaterialApp(home: MyForm()));
}
//表单
class MyForm extends StatefulWidget {
const MyForm({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _FormState();
}
class _FormState extends State<MyForm> {
//使用Map收集数据,而非TextEditingController
final Map<String, dynamic> _inputMap = {};
//FormState为Form的状态类
final GlobalKey _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("MyForm"),
),
body: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextFormField(
maxLines: 1,
maxLength: 64,
//自动获取焦点
autofocus: true,
//自动校验模式
autovalidateMode: AutovalidateMode.disabled,
decoration: const InputDecoration(
labelText: "账号",
hintText: "手机或邮箱",
prefixIcon: Icon(Icons.person)),
onChanged: (val) {
_inputMap['acct'] = val;
},
validator: (val) {
print('acct validator');
return val!.trim().isNotEmpty ? null : "账号不能为空";
},
),
TextFormField(
maxLines: 1,
maxLength: 12,
//隐藏文本
obscureText: true,
decoration: const InputDecoration(
labelText: "密码",
hintText: "登录密码",
prefixIcon: Icon(Icons.lock)),
onChanged: (val) {
_inputMap['pass'] = val;
},
validator: (val) {
print('pass validator');
return val!.trim().length > 5 ? null : "密码不能少于6位";
},
),
TextButton(
child: const Text('登录'),
onPressed: () {
//调用validate触发所有FormField的validate回调
if ((_formKey.currentState as FormState).validate()) {
print("验证通过: $_inputMap");
}
},
)
],
),
),
);
}
}