和TextField属性基本一致,在其基础上增加字段的校验和提交的回调,FormState的save会触发onSaved回调。

相关组件

TextField Form

TextFormField基本使用

基本属性和TextField一致,详见之
【validator】 : 验证函数 【FormFieldValidator
【onFieldSubmitted】 : 提交回调 【ValueChanged
【onSaved】 : 表单save时回调 【FormFieldSetter
119.gif

  1. import 'package:flutter/material.dart';
  2. class CustomTextFormField extends StatefulWidget {
  3. @override
  4. _CustomTextFormFieldState createState() => _CustomTextFormFieldState();
  5. }
  6. class _CustomTextFormFieldState extends State<CustomTextFormField> {
  7. GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  8. @override
  9. Widget build(BuildContext context) {
  10. return Container(
  11. child: Form(
  12. key: _formKey,
  13. child:
  14. Stack(
  15. alignment: Alignment.centerRight,
  16. children: <Widget>[
  17. Container(
  18. width: 350,
  19. child: UnconstrainedBox(
  20. child: Container(
  21. width: 200,
  22. height: 70,
  23. child: TextFormField(
  24. style: TextStyle(textBaseline: TextBaseline.alphabetic),
  25. decoration: InputDecoration(
  26. border: OutlineInputBorder(),
  27. labelText: 'username',
  28. ),
  29. validator: _validateUsername,
  30. onFieldSubmitted: _onFieldSubmitted,
  31. onSaved: _onSaved,
  32. ),
  33. ),
  34. ),
  35. ),
  36. Positioned(
  37. top: 0, right: 0, child: _buildSubmitButton(context)),
  38. ],
  39. ),
  40. ),
  41. );
  42. }
  43. String _validateUsername(value) {
  44. if (value.isEmpty) {
  45. return '用户名不能为空';
  46. }
  47. return null;
  48. }
  49. _onSaved(value){
  50. print('onSaved:'+value);
  51. }
  52. void _onFieldSubmitted(value) {
  53. print('onFieldSubmitted:'+value);
  54. }
  55. RaisedButton _buildSubmitButton(BuildContext context) {
  56. return RaisedButton(
  57. color: Colors.blue,
  58. shape: CircleBorder(
  59. side: BorderSide(width: 2.0, color: Color(0xFFFFDFDFDF)),
  60. ),
  61. onPressed: _onSubmit,
  62. child: Icon(
  63. Icons.check,
  64. color: Colors.white,
  65. ),
  66. );
  67. }
  68. _onSubmit(){
  69. _formKey.currentState.save();
  70. if (_formKey.currentState.validate()) {
  71. FocusScope.of(context).requestFocus(FocusNode());
  72. }
  73. }
  74. }