22 Flutter 时间日期组件

Flutter自带日期组件,异步方法的数据获取,日期组件显示中文

1. showDatePicker, 不是一个控件,是一个函数

1.属性

context
initialDate初始化时间
firstDate开始时间,时间控件选择器从这个时间开始
lastDate结束时间
initialDatePickerModeday:初始化显示天,year:初始化先选择年
textDirection文本方向
cancelText取消文字
confirmText确认文字
locale国际化

2.日期和时间戳转换

var now = new DateTime.now();
print(now.millisecondsSinceEpoch); // 时间戳,单位毫秒

时间戳转换日期

var now = new DataTime.now();
var a = now.millisecondsSinceEpoch;
print(DataTime.fromMillisecondsSinceEpoch(a)); //2020-11-20 12:12:10

3.时间选择器

//调起时间选择器
  void _showTimePicker() async {
    // 获取异步方法里面的值的第二种方式:async+await
    //await的作用是等待异步方法showDatePicker执行完毕之后获取返回值
    var result = await showTimePicker(
      context: context,
      initialTime: _selectedTime, //选中的时间
    );

    //将选中的值传递出来
    setState(() {
      if (result != null) {
        this._selectedTime = result;
      }
    });
  }

2.国际化

1.****配置flutter_localizations依赖****

flutter_localizations:
    sdk: flutter 

2.导入国际化的包flutter_localizations.dart

import 'package:flutter_localizations/flutter_localizations.dart';

3.设置国际化


class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      onGenerateRoute: prefix0.onGenerateRoute,
      initialRoute: "/",
      //配置如下两个国际化的参数
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: [
        const Locale("zh", "CH"),
        const Locale("en", "US")
      ],
    );
  }
}

4.解决冲突方式,date_format 中local于系统自带冲突,可以采用下面方式

import 'package:date_format/date_format.dart' hide Locale; //隐藏
import 'package:date_format/date_format.dart' as format; //别名
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart' hide Locale;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //配置如下两个国际化的参数
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: [
        //此处
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
      home: Scaffold(
        //标题栏
        appBar: AppBar(
          title: Text("Flutter Demo"),
        ),
        //内容区域
        body: DatePickerPubPage(),
      ),
      //主题
      theme: ThemeData(primarySwatch: Colors.red),
    );
  }
}

class DatePickerPubPage extends StatefulWidget {
  @override
  _DatePickerPubPageState createState() => _DatePickerPubPageState();
}

class _DatePickerPubPageState extends State<DatePickerPubPage> {
  DateTime _selectedDateTime = DateTime.now(); //获取当前日期

  var nowTime = DateTime.now(); //获取当前时间

  DateTime _selectedDate = DateTime.now(); //当前选中的日期
  TimeOfDay _selectedTime = TimeOfDay.now(); //当前选中的时间

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(nowTime); //2020-02-11 08:51:14.165032

    //当前时间转换为时间戳
    var a = nowTime.millisecondsSinceEpoch; //13位时间戳
    print(a); //1581382274165

    //将时间戳转换成时间
    var aTime = DateTime.fromMillisecondsSinceEpoch(a);
    print(aTime); //2020-02-11 08:51:14.165

    //Flutter的第三方库 date_format 的使用
    //2020-02-11 08:51:14.165 时间转换为  2020-02-11

    print(formatDate(DateTime.now(), [yyyy, "-", mm, "-", dd]));

    //2020-02-11 08:51:14.165 时间转换为 2020年02月11日
    print(formatDate(DateTime.now(), [yyyy, "年", mm, "月", dd, "日"]));
  }

  //调起日期选择器
  void _showDatePicker() {
    //获取异步方法里面的值的第一种方式:then
    showDatePicker(
      //如下四个参数为必填参数
      context: context,
      initialDate: _selectedDate,
      //选中的日期
      firstDate: DateTime(1980),
      //日期选择器上可选择的最早日期
      lastDate: DateTime(2100),
      //日期选择器上可选择的最晚日期
      cancelText: "你好",
      // locale:Locale("zh")
    ).then((selectedValue) {
      setState(() {
        //将选中的值传递出来
        if (selectedValue != null) {
          print(selectedValue);
          this._selectedDate = selectedValue;
        }
      });
    }).catchError((err) {
      print(err);
    });
  }

  //调起时间选择器
  void _showTimePicker() async {
    // 获取异步方法里面的值的第二种方式:async+await
    //await的作用是等待异步方法showDatePicker执行完毕之后获取返回值
    var result = await showTimePicker(
      context: context,
      initialTime: _selectedTime, //选中的时间
    );

    //将选中的值传递出来
    setState(() {
      if (result != null) {
        this._selectedTime = result;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //可以通过在外面包裹一层InkWell来让某组件可以响应用户事件
            InkWell(
              onTap: () {
                //调起日期选择器
                _showDatePicker();
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(formatDate(
                      this._selectedDate, [yyyy, "-", mm, "-", "dd"])),
                  Icon(Icons.arrow_drop_down)
                ],
              ),
            ),

            InkWell(
              onTap: () {
                //调起时间选择器
                _showTimePicker();
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("${this._selectedTime.format(context)}"),
                  Icon(Icons.arrow_drop_down)
                ],
              ),
            )
          ],
        )
      ],
    );
  }
}

3.第三方时间组件

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        //标题栏
        appBar: AppBar(
          title: Text("Flutter Demo"),
        ),
        //内容区域
        body: DatePickerPage(),
      ),
      //主题
      theme: ThemeData(primarySwatch: Colors.red),
    );
  }
}

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

  @override
  _DatePickerPageState createState() {
    return _DatePickerPageState();
  }
}

class _DatePickerPageState extends State<DatePickerPage> {
  var _nowDate = DateTime.now();

  _timePickerWidget() {
    DatePicker.showDatePicker(context,
        //配置语言
        locale: DateTimePickerLocale.zh_cn,
        //日期样式
        pickerTheme: DateTimePickerTheme(
          confirm: Text(
            "确定",
            style: TextStyle(fontSize: 20,color: Colors.red),
          ),
          cancel: Text(
            "取消",
            style: TextStyle(fontSize: 20),
          ),
          itemHeight: 20,
          itemTextStyle: TextStyle(fontSize: 20,color:Colors.green)
        ),
        //最小日期限制
        minDateTime: DateTime.parse("1965-01-01"),
        //最大日期限制
        maxDateTime: DateTime.parse("2100-01-01"),
        //初试日期
        initialDateTime: DateTime.now(),
        dateFormat: "yyyy-MM-dd EEE,H时:m分",
        pickerMode: DateTimePickerMode.datetime,
        //show datetime 配置为datetime格式的时候 dateFormat必须要加上时分的格式
        //在日期发生改变的时候实时更改日期
        onChange: (date, List<int> index) {
      setState(() {
        _nowDate = date;
      });
    },
        //点击确认后才更改日期
        onConfirm: (date, List<int> index) {
      setState(() {
        _nowDate = date;
      });
    });
  }

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("CupertinoDatePickerPage"),
      ),
      body: Column(
        children: <Widget>[
          InkWell(
            onTap: _timePickerWidget,
            child: Row(
              children: <Widget>[
                Text(dateFormat.formatDate(_nowDate, [
                  dateFormat.yyyy,
                  '年',
                  dateFormat.mm,
                  '月',
                  dateFormat.dd,
                  '日',
                  dateFormat.HH,
                  '时',
                  dateFormat.n,
                  '分'
                ])),
                Icon(Icons.keyboard_arrow_down)
              ],
            ),
          )
        ],
      ),
    );
  }
}

4. flutter 1.20以后 将 DiagnosticableMixin移除了,更新为Diagnosticable

img

img

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值