Flutter表单(TextField,Checkbox,Radio以及Switch)

TextField

属性

属性 描述
maxLines 设置此参数可以把文本框改为多行文本框
onChanged 文本框改变的时候触发的事件
decoration hintText :类似 html 中的 placeholder
border :配置文本框边框OutlineInputBorder 配合使用
labelText :lable 的名称
labelStyle :配置 lable 的样式
obscureText 把文本框框改为密码框
controller controller 结合 TextEditingController()可以配置表单默认显示的内容

下面的例子中我们在Scaffold内部有嵌套了一个SingleChildScrollView,因为在没有嵌套时遇到问题“bottom overflowed by 12 pixels”,问题是由于当键盘弹出时,组件加起来高度超过最外层组件高度(这里是屏幕高度)


// ignore_for_file: prefer_const_constructors_in_immutables, prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'package:flutter/material.dart';

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

  @override
  _TextFieldDemoPageState createState() => _TextFieldDemoPageState();
}

class _TextFieldDemoPageState extends State<TextFieldDemoPage> {
    
    
  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('表单演示页面'),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(children: [
          TextField(
            decoration: InputDecoration(
              hintText: "请输入内容",
              border: OutlineInputBorder()
            ),
            
          ),
          SizedBox(height: 20,),
          TextField(
            obscureText: true,
            decoration: InputDecoration(
              hintText: "密码框",
              border: OutlineInputBorder()
            ),            
          ),
          SizedBox(height: 20,),
          TextField(
            decoration: InputDecoration(
              labelText: "用户名",
              border: OutlineInputBorder()
            ),            
          ),
          SizedBox(height: 20,),
          TextField(
            decoration: InputDecoration(
              icon: Icon(Icons.people),
              hintText: "请输入用户名"
            ),            
          ),
        ],),
        )
        ),
    );
  }
}

在这里插入图片描述

获取TextField值

在onChanged中获取
下面代码中几点需要注意的:

  1. Container中width: double.infinity,是设置宽度自适应屏幕(和屏幕宽度相同)
  2. var username = new TextEditingController();还用到了controller给TextField赋初值,如果不需要赋初值直接var username即可,不需要new TextEditingController();直接在onChanged中获取value即为TextField中的值
// ignore_for_file: prefer_const_constructors_in_immutables, prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'package:flutter/material.dart';

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

  @override
  _TextFieldDemoPageState createState() => _TextFieldDemoPageState();
}

class _TextFieldDemoPageState extends State<TextFieldDemoPage> {
    
    
  var username = new TextEditingController();
  var password;

  @override
  void initState() {
    
    
    super.initState();
    username.text = "初始值";
  }

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('表单演示页面'),
      ),
      body: Padding(
          padding: EdgeInsets.all(20),
          child: SingleChildScrollView(
              child: Column(
            children: [
              TextField(
                decoration: InputDecoration(hintText: "请输入用户名"),
                controller: username,
                onChanged: (value) {
    
    
                  setState(() {
    
    
                    username.text = value;
                  });
                },
              ),
              SizedBox(
                height: 15,
              ),
              TextField(
                obscureText: true,
                decoration: InputDecoration(hintText: "请输入密码"),
                onChanged: (value) {
    
    
                  setState(() {
    
    
                    password = value;
                  });
                },
              ),
              SizedBox(
                height: 15,
              ),
              Container(
                width: double.infinity,
                child: ElevatedButton(
                    onPressed: () {
    
    
                      print(username.text);
                      print(password);
                    },
                    child: Text("登录")),
              )
            ],
          ))),
    );
  }
}

在这里插入图片描述

Checkbox和CheckboxListTile组件(复选框)

Checkbox 常见属性:

属性 描述
value true 或者 false
onChanged 改变的时候触发的事件
activeColor 选中的颜色、背景颜色
checkColor 选中的颜色、Checkbox 里面对号的颜色

CheckboxListTile 常见属性:

属性 描述
value true 或者 false
onChanged 改变的时候触发的事件
activeColor 选中的颜色、背景颜色
title 标题
subtitle 二级标题
secondary 配置图标或者图片
selected 选中的时候文字颜色是否跟着改变
import 'package:flutter/material.dart';

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

  @override
  _CheckBoxDemoState createState() => _CheckBoxDemoState();
}

class _CheckBoxDemoState extends State<CheckBoxDemo> {
    
    
  bool flag = true;
  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("checkbox"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Checkbox(
                value: flag,
                onChanged: (value) {
    
    
                  setState(() {
    
    
                    flag = value!;
                    print(flag);
                  });
                },
                activeColor: Colors.yellow,
              ),
            ],
          ),
          Row(
            children: [Text(flag ? "选中" : "未选中")],
          ),
          SizedBox(
            height: 20,
          ),
          Divider(),
          CheckboxListTile(
              value: flag,
              onChanged: (value) {
    
    
                setState(() {
    
    
                  flag = value!;
                });
              },
              title: Text("标题"),
              subtitle: Text("这是二级标题"),
              secondary: Icon(Icons.help),
          )
        ],
      ),
    );
  }
}

(演示效果上面为CheckBox下面为CheckboxListTile)
未选中
选中

Radio和RadioListTile(单选框)

Radio 常用属性:

属性 描述
value 单选的值
onChanged 改变时触发
activeColor 选中的颜色、背景颜色
groupValue 选择组的值

RadioListTile 常用属性:

属性 描述
value 单选的值
onChanged 改变的时候触发的事件
activeColor 选中的颜色、背景颜色
title 标题
subtitle 二级标题
secondary 配置图标或者图片
groupValue 选择组的值
selected true或false,选中时条目高亮
// ignore_for_file: prefer_const_constructors, prefer_typing_uninitialized_variables

import 'package:flutter/material.dart';

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

  @override
  _RadioDemoState createState() => _RadioDemoState();
}

class _RadioDemoState extends State<RadioDemo> {
    
    
  var sex;
  var s1;
  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("Radio"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            Row(
              children: [
                Text("男:"),
                Radio(
                    value: 1,
                    groupValue: sex,
                    onChanged: (value) {
    
    
                      setState(() {
    
    
                        sex = value;
                      });
                    }),
                SizedBox(width: 10),
                Text("女:"),
                Radio(
                    value: 2,
                    groupValue: sex,
                    onChanged: (value) {
    
    
                      setState(() {
    
    
                        sex = value;
                      });
                    }),
              ],
            ),
            Row(
              children: [
                Text("$sex"),
                Text(sex == 1 ? "男" : "女"),
              ],
            ),
            SizedBox(height: 20),
            RadioListTile(
                value: 1,
                groupValue: s1,
                title: Text("这是一级标题"),
                subtitle: Text("这是二级标题"),
                secondary: Icon(Icons.help),
                selected: s1==1,
                onChanged: (value) {
    
    
                  setState(() {
    
    
                    s1 = value;
                  });
                }),
            RadioListTile(
                value: 2,
                groupValue: s1,
                title: Text("这是一级标题"),
                subtitle: Text("这是二级标题"),
                secondary: Icon(Icons.help),
                selected: s1==2,
                onChanged: (value) {
    
    
                  setState(() {
    
    
                    s1 = value;
                  });
                }),
          ],
        ),
      ),
    );
  }
}

(演示效果上面为Radio下面为RadioListTile)
在这里插入图片描述

Switch开关

属性 描述
value 单选的值
onChanged 改变时触发
activeColor 选中的颜色、背景颜色
// ignore_for_file: prefer_const_constructors, prefer_typing_uninitialized_variables

import 'package:flutter/material.dart';

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

  @override
  _RadioDemoState createState() => _RadioDemoState();
}

class _RadioDemoState extends State<RadioDemo> {
    
    
  bool flag = true;
  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("Radio"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            Switch(
                value: flag,
                onChanged: (v) {
    
    
                  setState(() {
    
    
                    flag = v;
                    print(flag);
                  });
                }),
          ],
        ),
      ),
    );
  }
}

在这里插入图片描述

使用上面组件完成一个简单的信息登记界面

// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';

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

  @override
  _FormDemoPageState createState() => _FormDemoPageState();
}

class _FormDemoPageState extends State<FormDemoPage> {
    
    
  late String username;
  var sex;
  String info = "";

  List hobby = [
    {
    
    "checked": true, "title": "吃饭"},
    {
    
    "checked": false, "title": "睡觉"},
    {
    
    "checked": true, "title": "写代码"}
  ];

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

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

  @override
  Widget build(BuildContext context) {
    
    
    return Scaffold(
      appBar: AppBar(
        title: Text("学员信息登记"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            TextField(
              decoration: InputDecoration(hintText: "输入用户信息"),
              onChanged: (v) {
    
    
                setState(() {
    
    
                  username = v;
                });
              },
            ),
            SizedBox(height: 10),
            Row(
              children: [
                Text("男"),
                Radio(value: 1, groupValue: sex, onChanged: _sexChanged),
                SizedBox(width: 20),
                Text("女"),
                Radio(value: 2, groupValue: sex, onChanged: _sexChanged),
              ],
            ),
            SizedBox(height: 10),
            //爱好
            Column(
              children: _getHobby(),
            ),
            TextField(
              maxLength: 4,
              decoration: InputDecoration(hintText: "输入用户信息",border: OutlineInputBorder()),
              onChanged: (value) {
    
    
                setState(() {
    
    
                  info = value;
                });
              },
            ),
            SizedBox(height: 10),
            Container(
              width: double.infinity,
              height: 40,
              child: ElevatedButton(
                child: Text("提交信息"),
                onPressed: () {
    
    
                  print(sex);
                  print(username);
                  print(hobby);
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

在这里插入图片描述

需要注意的就是下面的代码,我们需要四个CheckBox,这里通过for循环动态创建

 List hobby = [
    {
    
    "checked": true, "title": "吃饭"},
    {
    
    "checked": false, "title": "睡觉"},
    {
    
    "checked": true, "title": "写代码"}
  ];

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

猜你喜欢

转载自blog.csdn.net/m0_46527751/article/details/122589250
今日推荐