flutter 中的From表單
阿新 • • 發佈:2021-06-06
通用方法
做過前端的都應該提交過表單,以文字輸入為例flutter中提供了通用的TextField元件
TextField(
decoration: InputDecoration(labelText: '產品名稱'),
onChanged: (String value) {
setState(() {
_name = value;
});
print(value);
},
);
onChanged
回撥一個包含String value 引數的方法,通過setState方法給屬性賦值.
TextFormField
//表單狀態 GlobalKey<FormState> _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { // TODO: implement build return Container( margin: EdgeInsets.all(10.0), child: Form( //繫結狀態屬性 key: _formKey, child: ListView( children: <Widget>[ _buildNameText(), _buildDescriptionText(), _buildPriceText(), Container( padding: EdgeInsets.all(10.0), child: RaisedButton(child: Text('新增'), onPressed: _submitValues), ) ], ))); } Widget _buildNameText() { return TextFormField( decoration: InputDecoration(labelText: '產品名稱'), validator: (String value) { //刪除首尾空格 if (value.isEmpty || value.trim().length <= 5) { return '名稱字數必須大於5'; } }, onSaved: (String value) { text = value; }, ); }
flutter專門為表單提交提供了一套解決方法,主要由Form
,TextFormField
,元件,GlobalKey<FormState>
屬性,組成.onSaved回撥一個引數為String value的方法,呼叫時機與onChanged不同,會在_formKey.currentState.save()
執行時呼叫.TextFormField中的validator
是一個驗證器,同樣回撥一個方法,可以根據自定義條件返回錯誤資訊.它的會在_formKey.currentState.validate();
方法呼叫是回撥.
原始碼地址 文件:TextField TextFormField
轉載於:https://my.oschina.net/roycehe/blog/2048757