1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| class FormWidgetDemo extends StatefulWidget { const FormWidgetDemo({super.key});
@override State<FormWidgetDemo> createState() => _FormWidgetDemoState(); }
class _FormWidgetDemoState extends State<FormWidgetDemo> {
final formGlobalKey = GlobalKey<FormState>(); late String username, password;
void _submitFormData(){ formGlobalKey.currentState!.save(); formGlobalKey.currentState!.validate(); if ( formGlobalKey.currentState!.validate() ) { Get.snackbar("提示", "登录成功!"); debugPrint('用户名: $username'); debugPrint('密码 $password');
} else { Get.snackbar( "提示", "用户名密码不正确!", colorText: Colors.red
); }
}
@override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(15), child: Form( key: formGlobalKey, autovalidateMode: AutovalidateMode.disabled, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormField( decoration: const InputDecoration( labelText: '用户名', hintText: '请输入用户名!', prefixIcon: Icon(Icons.people), border: OutlineInputBorder() ), onSaved: (newValue) { username = newValue!; }, validator: (value){ if( value!.isEmpty ) { return '用户名是必填项!'; } return null; }, ), const SizedBox(height: 15,), TextFormField( obscureText: true, decoration: const InputDecoration( labelText: '密码', hintText: '请输入密码!', prefixIcon: Icon(Icons.password), border: OutlineInputBorder() ), onSaved: (newValue) { password = newValue!; }, validator: (value){ if( value!.isEmpty ) { return '密码是必填项!'; } return null; }, ), const SizedBox(height: 25,), Container( width: double.infinity, child: ElevatedButton( onPressed: _submitFormData, child: const Text('登录', style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w200),), ), ) ], ) ) ); } }
|