Flutter入门(五)--表单+单选/多选+日期+轮播+对话框

* 表单

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

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          TextField(),
          SizedBox(height: 10),
          TextField(
            decoration: InputDecoration(
              hintText: "请输入搜索的内容",
              border: OutlineInputBorder(),
            ),
          ),
          SizedBox(height: 10),
          TextField(
            maxLines: 4,
            decoration: InputDecoration(
              hintText: "多行文本框",
              border: OutlineInputBorder(),
            ),
          ),
          SizedBox(height: 10),
          TextField(
            obscureText: true,
            decoration: InputDecoration(
              hintText: "密码框",
              border: OutlineInputBorder(),
            ),
          ),
          SizedBox(height: 10),
          TextField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: "用户名",
            ),
          ),
          SizedBox(height: 10),
          TextField(
            decoration: InputDecoration(
              icon: Icon(Icons.people),
              hintText: "请输入用户名",
            ),
          ),
        ],
      ),
    );
  }
}

效果图

 

* CheckBox多选

import 'package:flutter/material.dart';

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

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

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

效果图

 

* Radio单选

import 'package:flutter/material.dart';

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

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

class _RadioPageState extends State<RadioPage> {
  var sex = 1;
  bool flag = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Radio"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
            // Row(
            //   children: <Widget>[
            //     Text("男"),
            //     Radio(
            //       value: 1,
            //       onChanged: (v) {
            //         setState(() {
            //           this.sex = v;
            //         });
            //       },
            //       groupValue: this.sex,
            //     ),
            //     Text("女"),
            //     Radio(
            //       value: 2,
            //       onChanged: (v) {
            //         setState(() {
            //           this.sex = v;
            //         });
            //       },
            //       groupValue: this.sex,
            //     )
            //   ],
            // ),
            // Row(
            //   children: <Widget>[
            //     Text(this.sex == 1 ? "男" : "女"),
            //   ],
            // ),
            SizedBox(
              height: 20,
            ),
            RadioListTile(
              value: 1,
              onChanged: (v) {
                setState(() {
                  this.sex = v;
                });
              },
              groupValue: this.sex,
              title: Text("标题"),
              subtitle: Text("二级标题"),
              secondary: Icon(Icons.help),
              selected: this.sex == 1,
            ),
            RadioListTile(
              value: 2,
              onChanged: (v) {
                setState(() {
                  this.sex = v;
                });
              },
              groupValue: this.sex,
              title: Text("标题"),
              subtitle: Text("二级标题"),
              secondary: Icon(Icons.help),
              selected: this.sex == 2,
            ),
            SizedBox(height: 20),
            Switch(
              value: this.flag,
              onChanged: (v) {
                setState(() {
                  print(v);
                  this.flag = v;
                });
              },
            )
          ],
        ),
      ),
    );
  }
}

效果图

 

* 日期选择showTimePicker+showDatePicker

import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';

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

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

class _DatePageState extends State<DatePage> {
  DateTime _nowDate = DateTime.now();
  var _nowTime = TimeOfDay(hour: 12, minute: 20);
  _showDatePicker() {
    showDatePicker(
      context: context,
      initialDate: _nowDate,
      firstDate: DateTime(1980),
      lastDate: DateTime(2100),
    ).then((result) {
      setState(() {
        this._nowDate = result;
      });
    });
  }

  _showTimePicker() {
    showTimePicker(
      context: context,
      initialTime: _nowTime,
    ).then((result) {
      setState(() {
        this._nowTime = result;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("DatePicker"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          InkWell(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text("${formatDate(_nowDate, [yyyy, '年', mm, '月', dd, '日'])}"),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: () {
              _showDatePicker();
            },
          ),
          SizedBox(height: 10),
          InkWell(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text("${_nowTime.format(context)}"),
                Icon(Icons.arrow_drop_down)
              ],
            ),
            onTap: () {
              _showTimePicker();
            },
          ),
        ],
      ),
    );
  }
}

国际化方案http://bbs.itying.com/topic/5cfb2a12f322340b2c90e764

效果图

 

* 第三方日期库

库地址https://pub.dev/packages/datetime_picker_formfield

import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:date_format/date_format.dart';

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

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

class _DatePubPageState extends State<DatePubPage> {
  DateTime _dateTime = DateTime.now();
  _showDatePicker() {
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse('1980-01-01'),
      maxDateTime: DateTime.parse('2020-12-30'),
      initialDateTime: _dateTime,
      dateFormat: 'yyyy-MM-dd',
      locale: DateTimePickerLocale.zh_cn,
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onChange: (dateTime, List<int> index) {
        setState(() {
          _dateTime = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          _dateTime = dateTime;
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("第三方日期"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                child: Row(
                  children: <Widget>[
                    Text("${formatDate(_dateTime,[yyyy,'年',mm,'月','dd','日'])}"),
                    Icon(Icons.arrow_drop_down),
                  ],
                ),
                onTap: _showDatePicker,
              )
            ],
          )
        ],
      ),
    );
  }
}

效果图

 

* 轮播图

库地址https://pub.dev/packages/flutter_swiper

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

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

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

class _SwiperPageState extends State<SwiperPage> {
  List<Map> imgList = [
    {"url": "https://www.itying.com/images/flutter/2.png"},
    {"url": "https://www.itying.com/images/flutter/3.png"},
    {"url": "https://www.itying.com/images/flutter/4.png"},
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('轮播图组件'),
      ),
      body: new Swiper(
        itemBuilder: (BuildContext context, int index) {
          return new Image.network(
            imgList[index]['url'],
            fit: BoxFit.fill,
          );
        },
        itemCount: imgList.length,
        pagination: new SwiperPagination(), //底部分页器
        control: new SwiperControl(), //左右箭头
      ),
    );
  }
}

效果图

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

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

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

class _SwiperPageState extends State<SwiperPage> {
  List<Map> imgList = [
    {"url": "https://www.itying.com/images/flutter/2.png"},
    {"url": "https://www.itying.com/images/flutter/3.png"},
    {"url": "https://www.itying.com/images/flutter/4.png"},
    {"url": "https://www.itying.com/images/flutter/5.png"},
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('轮播图组件'),
      ),
      body: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            child: AspectRatio(
              aspectRatio: 16 / 9,
              child: Swiper(
                itemBuilder: (BuildContext context, int index) {
                  return new Image.network(
                    imgList[index]['url'],
                    fit: BoxFit.fill,
                  );
                },
                itemCount: imgList.length,
                pagination: new SwiperPagination(), //底部分页器
                // control: new SwiperControl(), //左右箭头
                autoplay: true,
              ),
            ),
          )
        ],
      ),
    );
  }
}

效果图

其他效果

 

 

* Dialog(对话框)

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

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

  _DialogPageState createState() => _DialogPageState();
}

class _DialogPageState extends State<DialogPage> {
  _alertDialog() async {
    var result = await showDialog(
        barrierDismissible: false, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示信息!"),
            content: Text("您确定要删除吗?"),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () {
                  print("取消");
                  Navigator.pop(context, 'Cancle');
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () {
                  print("确定");
                  Navigator.pop(context, "Ok");
                },
              )
            ],
          );
        });

    print(result);
  }

  _simpleDialog() async {
    var result = await showDialog(
        barrierDismissible: false, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return SimpleDialog(
            title: Text("选择内容"),
            children: <Widget>[
              SimpleDialogOption(
                child: Text("Option A"),
                onPressed: () {
                  print("Option A");
                  Navigator.pop(context, "A");
                },
              ),
              Divider(),
              SimpleDialogOption(
                child: Text("Option B"),
                onPressed: () {
                  print("Option B");
                  Navigator.pop(context, "B");
                },
              ),
              Divider(),
              SimpleDialogOption(
                child: Text("Option C"),
                onPressed: () {
                  print("Option C");
                  Navigator.pop(context, "C");
                },
              ),
              Divider(),
            ],
          );
        });

    print(result);
  }

  _modelBottomSheet() async {
    var result = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return Container(
            height: 220,
            child: Column(
              children: <Widget>[
                ListTile(
                  title: Text("分享 A"),
                  onTap: () {
                    Navigator.pop(context, "分享 A");
                  },
                ),
                Divider(),
                ListTile(
                  title: Text("分享 B"),
                  onTap: () {
                    Navigator.pop(context, "分享 B");
                  },
                ),
                Divider(),
                ListTile(
                  title: Text("分享 C"),
                  onTap: () {
                    Navigator.pop(context, "分享 C");
                  },
                )
              ],
            ),
          );
        });

    print(result);
  }

  _toast() {
    Fluttertoast.showToast(
        msg: "提示信息",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.black,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Dialog"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: Text('alert弹出框-AlertDialog '),
                onPressed: _alertDialog,
              ),
              SizedBox(height: 20),
              RaisedButton(
                child: Text('select弹出框-SimpleDialog'),
                onPressed: _simpleDialog,
              ),
              SizedBox(height: 20),
              RaisedButton(
                child: Text('ActionSheet底部弹出框-showModalBottomSheet'),
                onPressed: _modelBottomSheet,
              ),
              SizedBox(height: 20),
              RaisedButton(
                child: Text('toast-fluttertoast第三方库'),
                onPressed: _toast,
              ),
              // fluttertoast
            ],
          ),
        ));
  }
}

效果图

代码地址https://github.com/king1039/FlutterRoute/tree/master/lib

Flutter学习就暂告一段落,Flutter中文网的文档很齐全,Flutter实战电子书也很棒,大家可以自行学习

欢迎关注我的微信公众号:安卓圈

posted @ 2019-12-26 13:05  嘉禾世兴  阅读(1475)  评论(0编辑  收藏  举报