html 文本框 初始化,Flutter 文本框初始化时显示默认值
剛開始作Flutter文本框時候,使用的是TextField。彷佛大多數狀況下都沒有問題。代碼形式以下:html
class _FooState extends State {
TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = new TextEditingController(text: '初始化內容');
}
@override
Widget build(BuildContext context) {
return new Column(
children: [
new TextField(
// 當TextField 第一次建立時,controller會包含初始值,
// 當用戶修改文本框內容時,會修改controller的值。
controller: _controller,
),
new RaisedButton(
onPressed: () {
// 經過clear()能夠清空controller的值。
_controller.clear();
},
child: new Text('清空'),
),
],
);
}
}
問題1:動態建立文本框初始值
通常狀況下,直接使用這種方式,沒有任何問題。可是如今有一種狀況:api
問題1:當頁面文本框中的初始值是動態的,從后臺獲取到的時候,應該怎么辦呢?
這種狀況下,說明建立TextEditingController時,并不知道文本內容。這個時候若是動態修改controller的話,會報錯,根本無法使用。ide
這種狀況我根本沒遇到過,可是我以為Flutter確定有解決方法。因此我去找了一下Flutter的文檔,總算是沒有白找,找到了一個(https://api.flutter.dev/flutt... TextFormField。ui
文檔中有一句:spa
If a controller is not specified, initialValue can be used to give the automatically generated controller an initial value.
意思就是說,當不指定controller時,initialValue 就能夠自動生成controller的初始值。code
既然有解決方案,那么就是修改一下代碼便可。orm
class _FooState extends State {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return new Column(
children: [
new TextFormField(
initialValue: "初始值"
),
],
);
}
}
經過TextFormField這個組件,輕松解決掉這個問題了。htm
問題2: TextField和TextFormField的區別?
問題雖然解決了,可是如今又有另一個問題了:ci
問題2: TextField和TextFormField的區別是什么?何時使用TextField?何時使用TextFormField?
TextFormField:文檔
例如制做一個表單,表單中有用戶姓名,姓名必須包含@符號。這個時候就須要使用TextFormField這個組件
TextFormField(
autovalidateMode: AutovalidateMode.always, // 開啟自動驗證
decoration: const InputDecoration(
icon: Icon(Icons.person),
hintText: 'What do people call you?',
labelText: 'Name *',
),
onSaved: (String value) {
// 當用戶保存表單時,返回內容。
},
validator: (String value) { // 表單驗證
return value.contains('@') ? 'Do not use the @ char.' : null;
},
)
TextField:
例如制做一個顯示文本框,框中提示輸入文本框中的內容信息。
TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
),
)
總結:
若是須要使用保存、重置、驗證用戶輸入的狀況下,使用TextFormField。
若是只須要簡單的捕獲用戶的輸入行為,只須要使用TextField組件便可。
TextFormField須要個Form組件。
總結
以上是生活随笔為你收集整理的html 文本框 初始化,Flutter 文本框初始化时显示默认值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【剑指offer】面试题05:替换空格(
- 下一篇: Leetcode--870. 优势洗牌