flutter学习之基础组件(七)

flutter学习之基础组件(七)

本节主要学习输入框和选择控件以及日期组件



一、TextField文本输入框

TextField 表单常见属性:
在这里插入图片描述
在这里插入图片描述

具体各种实现代码:

class _FormContentState extends State<FormContent> {
  late TextEditingController _username;
  var textUsername = "初始值";

  @override
  void initState() {
    super.initState();
    _username = new TextEditingController(text: "初始值12312");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("表单演示页面"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: ListView(
          children: [
            TextField(),
            SizedBox(
              height: 10,
            ),
            TextField(
              decoration: InputDecoration(
                  hintText: "请输入账号", border: OutlineInputBorder() //设置外部边框
                  ),
            ),
            SizedBox(
              height: 10,
            ),
            TextField(
              maxLines: 2,
              decoration: InputDecoration(
                  hintText: "多行文本框", border: OutlineInputBorder() //设置外部边框
                  ),
            ),
            SizedBox(
              height: 10,
            ),
            TextField(
              obscureText: true, //设置显示密码框
              decoration: InputDecoration(
                  hintText: "密码框", border: OutlineInputBorder() //设置外部边框
                  ),
            ),
            SizedBox(
              height: 10,
            ),
            TextField(
              decoration: InputDecoration(
                  hintText: "用户名",
                  border: OutlineInputBorder(), //设置外部边框
                  labelText: "用户名"),
            ),
            SizedBox(
              height: 10,
            ),
            TextField(
              decoration: InputDecoration(
                hintText: "文本框设置图标",
                icon: Icon(Icons.people),
                border: OutlineInputBorder(), //设置外部边框
              ),
            ),
            SizedBox(
              height: 10,
            ),
            TextField(
                decoration: InputDecoration(
                  hintText: "获取文本内容",
                  border: OutlineInputBorder(), //设置外部边框
                ),
                controller: _username,
                onChanged: (value) {
                  setState(() {
                    _username.text = value;
                  });
                }),
            SizedBox(
              height: 20,
            ),
            Container(
              height: 40,
              width: double.infinity,
              child: ElevatedButton(
                  onPressed: () {
                    setState(() {
                      textUsername = _username.text;
                    });
                  },
                  child: Text("获取文本内容")),
            ),
            SizedBox(
              height: 20,
            ),
            Text(textUsername)
          ],
        ),
      ),
    );
  }
}

二、Checkbox、CheckboxListTile多选框组件

1.Checkbox

在这里插入图片描述
在这里插入图片描述

2.CheckboxListTile

在这里插入图片描述
在这里插入图片描述


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

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

class _CheckBoxContentState extends State<CheckBoxContent> {
  var flag = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("CheckBox演示页面"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Checkbox(
                    value: flag,
                    onChanged: (value) {
                      setState(() {
                        this.flag = value!;
                      });
                    },
                    checkColor: Colors.white,
                    activeColor: Colors.red),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [Text(this.flag ? "选中" : "未选中")],
            ),
            SizedBox(
              height: 20,
            ),
            Divider(),
            SizedBox(
              height: 20,
            ),
            CheckboxListTile(
              value: flag,
              onChanged: (value) {
                setState(() {
                  this.flag = value!;
                });
              },
              title: Text("选择"),
              subtitle: Text("请选择"),
              secondary: Icon(Icons.home),
            )
          ],
        ),
      ),
    );
  }
}

三、Radio、RadioListTile单选按钮组件和Switch开关组件

1.Radio

在这里插入图片描述

2.RadioListTile

在这里插入图片描述

3.Switch

在这里插入图片描述
在这里插入图片描述


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

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

class _RadioDemoContentState extends State<RadioDemoContent> {
  var _sex;
  var flag = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Radio演示页面"),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          children: [
            Text("Radio"),
            Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("男"),
                Radio(
                    value: 1,
                    groupValue: this._sex,
                    onChanged: (value) {
                      setState(() {
                        this._sex = value;
                      });
                    }),
                SizedBox(
                  width: 20,
                ),
                Text("女"),
                Radio(
                    value: 2,
                    groupValue: this._sex,
                    onChanged: (value) {
                      setState(() {
                        this._sex = value;
                      });
                    }),
              ],
            ),
            Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("${this._sex}"),
                Text(this._sex == 1 ? "男" : "女")
              ],
            ),
            Divider(),
            Text("RadioListTile"),
            Divider(),
            RadioListTile(
              value: 1,
              groupValue: this._sex,
              onChanged: (v) {
                setState(() {
                  this._sex = v;
                });
              },
              title: Text("选择1"),
              subtitle: Text("请选择1"),
              secondary: Icon(Icons.home),
            ),
            RadioListTile(
              value: 2,
              groupValue: this._sex,
              onChanged: (v) {
                setState(() {
                  this._sex = v;
                });
              },
              title: Text("选择2"),
              subtitle: Text("请选择2"),
              secondary: Icon(Icons.home),
            ),
            RadioListTile(
              value: 3,
              groupValue: this._sex,
              onChanged: (v) {
                setState(() {
                  this._sex = v;
                });
              },
              title: Text("选择3"),
              subtitle: Text("请选择3"),
              secondary: Icon(Icons.home),
            ),
            Divider(),
            Text("Switch开关"),
            Divider(),
            Switch(
                value: this.flag,
                onChanged: (v) {
                  setState(() {
                    this.flag = v;
                  });
                })
          ],
        ),
      ),
    );
  }
}

四、混合实现一个学员信息上报系统

通过TextFiled,CheckBoX,Radio实现一个上报数据页面,效果:
在这里插入图片描述
代码:


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

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

class _blendContentState extends State<blendContent> {
  late String _username;
  var _sex;
  String data = "";

  List hobby = [
    {"check": true, "titile": "吃饭"},
    {"check": false, "titile": "睡觉"},
    {"check": false, "titile": "打豆豆"},
  ];

  void _setRadioChanged(v) {
    setState(() {
      this._sex = v;
    });
  }

  List<Widget> _gerHobby() {
    List<Widget> list = [];
    for (var i = 0; i < hobby.length; i++) {
      list.add(Text(this.hobby[i]["titile"]+":"));
      list.add(Checkbox(
        value: this.hobby[i]["check"],
        onChanged: (bool? value) {
          setState(() {
            this.hobby[i]["check"] = value;
          });
        },
      ));
    }

    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("学员信息上报系统"),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          children: [
            TextField(
              decoration: InputDecoration(
                  hintText: "请输入用户信息",
                  border: OutlineInputBorder(), //设置外部边框
                  labelText: "用户名"),
              onChanged: (v) {
                setState(() {
                  this._username = v;
                });
              },
            ),
            Row(
              children: [
                Text("男:"),
                Radio(
                    value: 1,
                    groupValue: this._sex,
                    onChanged: this._setRadioChanged),
                SizedBox(
                  width: 20,
                ),
                Text("女:"),
                Radio(
                    value: 2,
                    groupValue: this._sex,
                    onChanged: this._setRadioChanged),
              ],
            ),
            Column(
              children: [
                Text("爱好:"),
                Row(
                  children: _gerHobby(),
                ),
              ],
            ),

            SizedBox(
              height: 20,
            ),
            Container(
              width: double.infinity,
              height: 40,
              child: ElevatedButton(
                onPressed: () {
                  setState(() {
                    data = "上报成功:姓名:${this._username}  性别:${this._sex} 爱好:${hobby}";
                  });
                },
                child: Text("上报信息"),
              ),
            ),
            Divider(),
            Text(data),
          ],
        ),
      ),
    );
  }
}

五、Flutter日期和时间戳

获取当前日期:

var _now = new DateTime.now();
print(_now);

日期转换成时间戳 13位

    var time = _now.microsecondsSinceEpoch;
    print(time); //转换成时间戳  1627454464973662

时间戳转化成日期:

    var dateTime = DateTime.fromMillisecondsSinceEpoch(1627454464973662);
    print(dateTime); //时间戳转时间

1.flutter自带日期组件和时间组件

flutter的日期组件是showDatePicker ,时间组件是showTimePicker,效果图如下:

在这里插入图片描述
相关代码:


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

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

class _SystemDataContentState extends State<SystemDataContent> {
  var _now = new DateTime.now();
  var _nowTime = TimeOfDay.fromDateTime(new DateTime.now());

  _showDataPicker() async {
    var result = await showDatePicker(
      context: context,
      initialDate: _now,
      firstDate: DateTime(1980),
      lastDate: DateTime(2025),
      locale: Locale('zh'),
    );

    setState(() {
      this._now = result!;
    });
  }

  _showTimePicker() async {
    var result = await showTimePicker(
      context: context,
      initialTime: _nowTime,
    );

    setState(() {
      this._nowTime = result!;
    });
  }

  @override
  void initState() {
    super.initState();

    print(_now);
    var time = _now.microsecondsSinceEpoch;
    print(time); //转换成时间戳  1627454464973662
    var dateTime = DateTime.fromMillisecondsSinceEpoch(1627454464973662);
    print(dateTime); //时间戳转时间
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("系统日期"),
      ),
      body: Padding(
        padding: EdgeInsets.all(10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            //给组件设置点击事件
            InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("${this._now}"),
                  Icon(Icons.all_inclusive_sharp)
                ],
              ),
              onTap: () {
                _showDataPicker();
              },
            ),
            InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("${formatDate(this._now, [yyyy, "", mm, "", dd])}"),
                  Icon(Icons.all_inclusive_sharp)
                ],
              ),
              onTap: () {
                _showDataPicker();
              },
            ),
            InkWell(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("${this._nowTime.format(context)}"),
                  Icon(Icons.timelapse)
                ],
              ),
              onTap: () {
                _showTimePicker();
              },
            ),
          ],
        ),
      ),
    );
  }
}

系统默认的日历是英文的,想要显示中文需要实现国际化,实现国际化首先需要在pubspec.yaml文件的
dependencies下添加:

#  国际化
  flutter_localizations:
    sdk: flutter

然后在主页MaterialApp下配置如下代码:

import 'package:flutter_localizations/flutter_localizations.dart'; 

 //下面两行配置国际化
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],

在这里插入图片描述
再然后在需要实现国际化的控件配置相关国际化的代码:
在这里插入图片描述
这样就实现国际化了

2.使用三方日期组件

先打开三方库查找网页https://pub.flutter-io.cn/
然后搜索flutter_datetime_picker并且按照集成文档,集成到项目中
在这里插入图片描述

  flutter_datetime_picker: ^1.5.1

效果图如下:
在这里插入图片描述
相关代码:


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

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

class _OtherDataContentState extends State<OtherDataContent> {

  DateTime _nowDate = new DateTime.now();
  TimeOfDay _nowTime = TimeOfDay.fromDateTime(new DateTime.now());

  _showDataPicker() {
    DatePicker.showDatePicker(context,
        showTitleActions: true,
        minTime: DateTime(2015, 3, 5),
        maxTime: DateTime(2025, 6, 7), onChanged: (date) {
      print('change $date');
    }, onConfirm: (date) {
      setState(() {
        this._nowDate = date;
      });
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  _showDataTimePicker() {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime(2015, 3, 5),
        maxTime: DateTime(2025, 6, 7), onChanged: (date) {
          print('change $date');
        }, onConfirm: (date) {
          setState(() {
            this._nowDate = date;
          });
        }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  _showTimePicker() {
    DatePicker.showTimePicker(context,
        showTitleActions: true,
        onChanged: (date) {
          print('change $date');
        }, onConfirm: (date) {
          setState(() {
            this._nowTime = date as TimeOfDay;
          });
        }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("三方日期组件flutter_datetime_picker"),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("${formatDate(this._nowDate, [yyyy, "-", mm, "-", dd])}"), Icon(Icons.arrow_drop_down)],
                ),
                onTap: _showDataPicker,
              ),
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("${this._nowTime.format(context)}"), Icon(Icons.arrow_drop_down)],
                ),
                onTap: _showTimePicker,
              ),
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [Text("${formatDate(this._nowDate, [yyyy, '-', mm, '-', dd," ",HH, ':', nn, ':', ss])}"), Icon(Icons.arrow_drop_down)],
                ),
                onTap: _showDataTimePicker,
              ),
            ],
          ),
        ),
      ),
    );
  }
}


总结

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值