FormField控件是單一表單字段,這個控件維護表單字段的當前狀態,以便更新和驗證錯誤能在UI中可見。TextField控件就是在FormField中包裝了一個Input控件(后面的文章講解),FormField維護輸入的當前值,使您不需要自己管理它,更容易一次保存,重置或驗證多個字段。
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
@override
_MyApp createState() => new _MyApp();
}
class _MyApp extends State<MyApp> {
String _lastName;
String _firstName;
GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
void _showMessage(String name) {
showDialog<Null>(
context: context,
child: new AlertDialog(
content: new Text(name),
actions: <Widget>[
new FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: new Text('確定')
)
]
)
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('表單輸入')
),
// Form:用于將多個表單控件組合在一起的容器
body: new Form(
key: _formKey,
child: new Column(
children: <Widget> [
// TextFieldd:包含輸入的表單控件,每個表單字段都應該在FormField控件中
new TextField(
labelText: '姓氏',
// onSaved:當通過Form.save()保存表單時調用的方法
onSaved: (InputValue value) {
_lastName = value.text;
}
),
new TextField(
labelText: '名字',
onSaved: (InputValue value) {
_firstName = value.text;
}
),
new Row(
children: <Widget> [
new RaisedButton(
child: new Text('重置'),
onPressed: () {
// reset():將此Form下的每個TextField重置為初始狀態
_formKey.currentState.reset();
_showMessage('姓名信息已經重置');
}
),
new RaisedButton(
child: new Text('提交'),
onPressed: () {
// save():保存Form下的每個TextField
_formKey.currentState.save();
_showMessage('你的姓名是'+_lastName+_firstName);
}
)
]
)
]
)
)
);
}
}
void main() {
runApp(new MaterialApp(
title: 'Flutter Demo',
home: new MyApp()
));
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。