Flutter(十九):Form 表單

Flutter 中常見的表單有 TextField 單行文本框弓柱,TextField 多行文本框膏执、CheckBox、Radio熟菲、Switch CheckboxListTile看政、RadioListTile朴恳、SwitchListTile、Slide.

擴展小知識點:占據(jù)整行

width: double.infinity

1 TextField

import 'package:flutter/material.dart';

class TextFieldDemoPage extends StatefulWidget {
  TextFieldDemoPage({Key key}) : super(key: key);

  _TextFieldDemoPageState createState() => _TextFieldDemoPageState();
}

class _TextFieldDemoPageState extends State<TextFieldDemoPage> {
  var _username = new TextEditingController(); //初始化的時候給表單賦值
  var _password = new TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _username.text = '初始值';
    _password.text = '初始值';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('表單演示頁面'),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          child: TextDemo(),
          // child: Column(
          //   children: <Widget>[
          //     TextField(
          //       decoration: InputDecoration(hintText: "請輸入用戶名"),
          //       controller: _username,
          //       onChanged: (value) {
          //         setState(() {
          //           _username.text = value;
          //         });
          //       },
          //     ),
          //     SizedBox(height: 10),
          //     TextField(
          //       obscureText: true,
          //       decoration: InputDecoration(hintText: "密碼"),
          //       controller: _password,
          //       onChanged: (value) {
          //         setState(() {
          //           this._password.text = value;
          //         });
          //       },
          //     ),
          //     SizedBox(height: 40),
          //     Container(
          //       width: double.infinity,
          //       height: 40,
          //       child: RaisedButton(
          //         child: Text("登錄"),
          //         onPressed: () {
          //           print(this._username.text);
          //           print(this._password.text);
          //         },
          //         color: Colors.blue,
          //         textColor: Colors.white,
          //       ),
          //     )
          //   ],
          // ),
        ));
  }
}

class TextDemo extends StatelessWidget {
  const TextDemo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          TextField(),
          SizedBox(height: 20),
          TextField(
            decoration: InputDecoration(
                hintText: "請輸入搜索的內(nèi)容", border: OutlineInputBorder()),
          ),
          SizedBox(height: 20),
          TextField(
            maxLines: 4,
            maxLength: 200,
            decoration: InputDecoration(
                hintText: "多行文本框", border: OutlineInputBorder()),
          ),
          SizedBox(height: 20),
          TextField(
            obscureText: true,
            decoration:
                InputDecoration(hintText: "密碼框", border: OutlineInputBorder()),
          ),
          SizedBox(height: 20),
          TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(), labelText: "用戶名")),
          SizedBox(height: 20),
          TextField(
              obscureText: true,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: "密碼",
                // labelStyle: TextStyle()
              )),
          SizedBox(height: 20),
          TextField(
              decoration: InputDecoration(
                  icon: Icon(Icons.people), hintText: "請輸入用戶名")),
        ],
      ),
    );
  }
}

效果

2 Checkbox允蚣、CheckboxListTile

import 'package:flutter/material.dart';

class TextFieldDemoPage extends StatefulWidget {
  TextFieldDemoPage({Key key}) : super(key: key);

  _TextFieldDemoPageState createState() => _TextFieldDemoPageState();
}

class _TextFieldDemoPageState extends State<TextFieldDemoPage> {
  var _username = new TextEditingController(); //初始化的時候給表單賦值
  var _password = new TextEditingController();

  var check = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _username.text = '初始值';
    _password.text = '初始值';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('表單演示頁面'),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          // child: TextDemo(),
          child: Column(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(hintText: "請輸入用戶名"),
                controller: _username,
                onChanged: (value) {
                  setState(() {
                    _username.text = value;
                  });
                },
              ),
              SizedBox(height: 10),
              TextField(
                obscureText: true,
                decoration: InputDecoration(hintText: "密碼"),
                controller: _password,
                onChanged: (value) {
                  setState(() {
                    this._password.text = value;
                  });
                },
              ),
              SizedBox(height: 40),
              Checkbox(
                onChanged: (v) {
                  setState(() {
                    this.check = v;
                  });
                },
                value: this.check,
                activeColor: Colors.orange,
              ),
              CheckboxListTile(
                value: this.check,
                onChanged: (v) {
                  setState(() {
                    this.check = v;
                  });
                },
                title: Text('標題'),
                subtitle: Text('副標題'),
                secondary: Image.asset("images/a.jpeg", fit: BoxFit.cover),
                selected: this.check,
              ),
              Divider(),
              CheckboxListTile(
                value: this.check,
                onChanged: (v) {
                  setState(() {
                    this.check = v;
                  });
                },
                title: Text('標題'),
                subtitle: Text('副標題'),
              ),
              Divider(),
              SizedBox(height: 40),
              Container(
                width: double.infinity,
                height: 40,
                child: RaisedButton(
                  child: Text("登錄"),
                  onPressed: () {
                    print(this._username.text);
                    print(this._password.text);
                  },
                  color: Colors.blue,
                  textColor: Colors.white,
                ),
              )
            ],
          ),
        ));
  }
}

3 Radio于颖、RadioListTile

import 'package:flutter/material.dart';

class TextFieldDemoPage extends StatefulWidget {
  TextFieldDemoPage({Key key}) : super(key: key);

  _TextFieldDemoPageState createState() => _TextFieldDemoPageState();
}

class _TextFieldDemoPageState extends State<TextFieldDemoPage> {
  var _username = new TextEditingController(); //初始化的時候給表單賦值
  var _password = new TextEditingController();

  var radioVal = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _username.text = '初始值';
    _password.text = '初始值';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('表單演示頁面'),
        ),
        body: Padding(
          padding: EdgeInsets.all(20),
          // child: TextDemo(),
          child: Column(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(hintText: "請輸入用戶名"),
                controller: _username,
                onChanged: (value) {
                  setState(() {
                    _username.text = value;
                  });
                },
              ),
              SizedBox(height: 10),
              TextField(
                obscureText: true,
                decoration: InputDecoration(hintText: "密碼"),
                controller: _password,
                onChanged: (value) {
                  setState(() {
                    this._password.text = value;
                  });
                },
              ),
              SizedBox(height: 40),
              Radio(
                onChanged: (v) {
                  setState(() {
                    this.radioVal = v;
                  });
                },
                value: 1,
                activeColor: Colors.orange,
                groupValue: this.radioVal,
              ),
              Radio(
                onChanged: (v) {
                  setState(() {
                    this.radioVal = v;
                  });
                },
                value: 2,
                activeColor: Colors.orange,
                groupValue: this.radioVal,
              ),
              RadioListTile(
                value: 1,
                onChanged: (v) {
                  setState(() {
                    this.radioVal = v;
                  });
                },
                title: Text('標題'),
                subtitle: Text('副標題'),
                secondary: Image.asset("images/a.jpeg", fit: BoxFit.cover),
                selected: this.radioVal == 1,
                groupValue: this.radioVal,
              ),
              Divider(),
              RadioListTile(
                value: 2,
                onChanged: (v) {
                  setState(() {
                    this.radioVal = v;
                  });
                },
                title: Text('標題'),
                subtitle: Text('副標題'),
                selected: this.radioVal == 2,
                groupValue: this.radioVal,
              ),
              Divider(),
              SizedBox(height: 40),
              Container(
                width: double.infinity,
                height: 40,
                child: RaisedButton(
                  child: Text("登錄"),
                  onPressed: () {
                    print(this._username.text);
                    print(this._password.text);
                  },
                  color: Colors.blue,
                  textColor: Colors.white,
                ),
              )
            ],
          ),
        ));
  }
}

效果

4 Switch

Switch(
  onChanged: (v) {},
  value: true,
),

5 綜合實例

import 'package:flutter/material.dart';

class FormDemoPage extends StatefulWidget {
  FormDemoPage({Key key}) : super(key: key);

  _FormDemoPageState createState() => _FormDemoPageState();
}

class _FormDemoPageState extends State<FormDemoPage> {
  String username;
  int sex = 1;
  String info = '';

  List hobby = [
    {"checked": true, "title": "吃飯"},
    {"checked": false, "title": "睡覺"},
    {"checked": true, "title": "寫代碼"}
  ];

  List<Widget> _getHobby() {
    List<Widget> tempList = [];

    for (var i = 0; i < this.hobby.length; i++) {
      tempList.add(Row(
        children: <Widget>[
          Text(this.hobby[i]["title"] + ":"),
          Checkbox(
              value: this.hobby[i]["checked"],
              onChanged: (value) {
                setState(() {
                  this.hobby[i]["checked"] = value;
                });
              })
        ],
      ));
    }
    return tempList;
  }

  void _sexChanged(value) {
    setState(() {
      this.sex = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("學員信息登記系統(tǒng)"),
      ),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(hintText: "輸入用戶信息"),
              onChanged: (value) {
                setState(() {
                  this.username = value;
                });
              },
            ),
            SizedBox(height: 10),
            Row(
              children: <Widget>[
                Text("男"),
                Radio(
                    value: 1,
                    onChanged: this._sexChanged,
                    groupValue: this.sex),
                SizedBox(width: 20),
                Text("女"),
                Radio(
                    value: 2, onChanged: this._sexChanged, groupValue: this.sex)
              ],
            ),

            //愛好
            SizedBox(height: 40),
            Column(
              children: this._getHobby(),
            ),

            // TextField(
            //   maxLines: 4,
            //   decoration: InputDecoration(
            //     hintText: "描述信息",
            //     border: OutlineInputBorder(),
            //   ),
            //   onChanged: (value) {
            //     setState(() {
            //       this.info = value;
            //     });
            //   },
            // ),

            SizedBox(height: 40),
            Container(
              // width: double.infinity,
              child: Wrap(
                alignment: WrapAlignment.start,
                children: <Widget>[
                  Container(
                    width: 120,
                    color: Colors.pink,
                    child: Row(
                      children: <Widget>[
                        Text('shuijiao'),
                        Checkbox(
                            value: this.hobby[1]['checked'],
                            onChanged: (v) {
                              setState(() {
                                this.setState(() {
                                  this.hobby[1]['checked'] = v;
                                });
                              });
                            }),
                      ],
                    ),
                  ),
                  Container(
                    width: 120,
                    child: Row(
                      children: <Widget>[
                        Text('shuijiao'),
                        Checkbox(
                            value: this.hobby[1]['checked'],
                            onChanged: (v) {
                              setState(() {
                                this.setState(() {
                                  this.hobby[1]['checked'] = v;
                                });
                              });
                            }),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            SizedBox(height: 40),
            Container(
              width: double.infinity,
              height: 40,
              child: RaisedButton(
                child: Text("提交信息"),
                onPressed: () {
                  print(this.sex);
                  print(this.username);
                  print(this.hobby);
                },
                color: Colors.blue,
                textColor: Colors.white,
              ),
            )
          ],
        ),
      ),
    );
  }
}

效果
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市嚷兔,隨后出現(xiàn)的幾起案子森渐,更是在濱河造成了極大的恐慌,老刑警劉巖冒晰,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件章母,死亡現(xiàn)場離奇詭異,居然都是意外死亡翩剪,警方通過查閱死者的電腦和手機乳怎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來前弯,“玉大人蚪缀,你說我怎么就攤上這事∷〕觯” “怎么了询枚?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長浙巫。 經(jīng)常有香客問我金蜀,道長的畴,這世上最難降的妖魔是什么渊抄? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮丧裁,結果婚禮上护桦,老公的妹妹穿的比我還像新娘。我一直安慰自己煎娇,他們只是感情好二庵,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著缓呛,像睡著了一般催享。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上哟绊,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天因妙,我揣著相機與錄音,去河邊找鬼。 笑死兰迫,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的炬称。 我是一名探鬼主播汁果,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼玲躯!你這毒婦竟也來了据德?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤跷车,失蹤者是張志新(化名)和其女友劉穎棘利,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體朽缴,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡善玫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了密强。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片茅郎。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖或渤,靈堂內(nèi)的尸體忽然破棺而出系冗,到底是詐尸還是另有隱情,我是刑警寧澤薪鹦,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布掌敬,位于F島的核電站,受9級特大地震影響池磁,放射性物質(zhì)發(fā)生泄漏奔害。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一地熄、第九天 我趴在偏房一處隱蔽的房頂上張望舀武。 院中可真熱鬧,春花似錦离斩、人聲如沸银舱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽寻馏。三九已至核偿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間轰绵,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工唧垦, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留液样,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓坊秸,卻偏偏與公主長得像澎怒,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子喷面,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354