今天我们来聊聊Flutter中的日期和日期选择器。

Flutter中的日期和时间戳

//日期时间戳转换
var _nowTime = DateTime.now();//获取当前时间
print(_nowTime);
print(_nowDate.millisecondsSinceEpoch); //13位时间戳 1575389234667
print(DateTime.fromMillisecondsSinceEpoch()); //时间戳转为日期2019-12-03 16:07:14.667

展示一个时间,会有多种形式,比如1970-01-01、1970/01/01、1970年01月01日,等等,那么我们如何把同一个时间根据需要转换成不同的格式呢?接下来我就为大家介绍一个Flutter中的第三方库。

Flutter的第三方库 date_format 

地址:https://pub.dev/packages/date_format

添加依赖:date_format: ^1.0.8

引入:

import 'package:date_format/date_format.dart';

简单来个例子,代码如下:

print(formatDate(DateTime.now(), [yyyy, "年", mm, "月", dd])); //2019年12月03

在开发项目的时候,我们经常会遇到选择时间或者选择日期的场景,接下来我将为大家介绍Flutter中自带的日期选择器和时间选择器。

调用Flutter自带的日期选择器组件和时间选择器组件

调起日期选择器的方法showDatePicker的返回值是Future,Future是一个异步类型,因此showDatePicker是一个异步方法。而要获取异步方法里面的数据,有两种方式。

1、获取异步方法里面的值的第一种方式:then

_showDatePicker(){
showDatePicker(
context: context,
initialDate: _nowDate, //选中的日期
firstDate: DateTime(), //日期选择器上可选择的最早日期
lastDate: DateTime(), //日期选择器上可选择的最晚日期
).then((result){
print(result);
});
}

2、获取异步方法里面的值的第二种方式:async+await

 _showDatePicker() async{
var result = await showDatePicker(
context: context,
initialDate: _nowDate, //选中的日期
firstDate: DateTime(), //日期选择器上可选择的最早日期
lastDate: DateTime(), //日期选择器上可选择的最晚日期
);
print(result);
}

两种方式都可以实现调用日期选择器。

Flutter自带的日期选择器是showDatePicker,时间选择器是showTimePicker。这两个选择器默认的显示效果都是英文的,我们是在中国,那么就需要将其显示成中文版的,这就涉及到Flutter的国际化的问题。

Flutter中的国际化

第一步:配置flutter_localizations依赖

找到pubspec.yaml,配置flutter_localizations:

flutter_localizations:
sdk: flutter

第二步:导入国际化的包flutter_localizations.dart

main.dart导入

import 'package:flutter_localizations/flutter_localizations.dart';

第三步,设置国际化

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")
],
);
}
}

如果操作系统是中文的,那么现在就可以显示中文了,如果操作系统不是中文的,那么还需要下面第四步。

第四步,在需要展示特定语言的组件中进行配置

//调起日期选择器
_showDatePicker() {
showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(),
lastDate: DateTime(),
locale: Locale("zh")//中文显示
).then((selectedValue) {
setState(() {
if (selectedValue != null) {
this._selectedDate = selectedValue;
}
});
});
}

这样配置好了之后,效果如下:

完整代码如下:

import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart'; class DatePicker extends StatefulWidget {
@override
State<StatefulWidget> createState() => _DatePicker();
} class _DatePicker extends State<DatePicker> {
DateTime _nowDate = DateTime.now(); //当前日期
TimeOfDay _nowTime = TimeOfDay.now(); //当前时间 //调起日期选择器
_showDatePicker(){
//获取异步方法里面的值的第一种方式:then
showDatePicker(
//如下四个参数为必填参数
context: context,
initialDate: _nowDate, //选中的日期
firstDate: DateTime(), //日期选择器上可选择的最早日期
lastDate: DateTime(), //日期选择器上可选择的最晚日期
).then((result){
print(result);
//将选中的值传递出来
setState(() {
this._nowDate = result;
});
});
}
// _showDatePicker() async{
// // 获取异步方法里面的值的第二种方式:async+await
// //await的作用是等待异步方法showDatePicker执行完毕之后获取返回值
// var result = await showDatePicker(
// context: context,
// initialDate: _nowDate, //选中的日期
// firstDate: DateTime(1900), //日期选择器上可选择的最早日期
// lastDate: DateTime(2100), //日期选择器上可选择的最晚日期
// );
// print(result);
// setState(() {
// this._nowDate = result;
// });
// } //调起时间选择器
_showTimePicker() async{
// 获取异步方法里面的值的第二种方式:async+await
//await的作用是等待异步方法showDatePicker执行完毕之后获取返回值
var result = await showTimePicker(
context: context,
initialTime: _nowTime, //选中的时间
);
print(result);
//将选中的值传递出来
setState(() {
this._nowTime = result;
});
} @override
Widget build(BuildContext context) {
var _date = formatDate(_nowDate, [yyyy, "-", mm, "-", dd]);
var _time = _nowTime.format(context);
return Scaffold(
appBar: AppBar(title: Text("日期时间选择器")),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
onTap:_showDatePicker,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("${_date}"),
Icon(Icons.arrow_drop_down)
],
),
),
InkWell(
onTap:_showTimePicker,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("${_time}"),
Icon(Icons.arrow_drop_down)
],
),
),
],
)
],
), );
}
}

调用Flutter的第三方时间选择器组件

上面介绍了系统给我们提供的日期时间选择器,但是有时候系统提供的选择器并不符合我们的要求,这时我们就可以到pub.dev上去寻找符合我们要求的日期选择器。

这里我们介绍一款Cupertino风格(即iOS风格)的日期选择器——flutter_cupertino_date_picker。

地址:https://pub.dev/packages/flutter_cupertino_date_picker

添加依赖:flutter_cupertino_date_picker: ^1.0.12

新建dart页面,引入:

import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';

这个插件提供了很多种格式,看你需要那种格式就找到那种格式的例子代码,看怎么使用。

1、首先date_picker_bottom_sheet为例

地址:https://github.com/dylanwuzh/flutter-cupertino-date-picker/blob/master/example/lib/date_picker_bottom_sheet.dart

一些引入date_format包,当前日期等参数我就不再写了。见上面代码

调起date_picker_bottom选择器,为了和上面的代码区分,我换了一个名字

//调起date_picker_bottom选择器
_cupertinoPicker(){
DatePicker.showDatePicker(
context,
pickerTheme: DateTimePickerTheme(
showTitle: true,
confirm: Text('确定', style: TextStyle(color: Colors.red)),
cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
),
minDateTime: DateTime.parse('2010-05-12'), //起始日期
maxDateTime: DateTime.parse('2021-11-25'), //终止日期
initialDateTime: _nowDate, //当前日期
dateFormat: 'yyyy-MMMM-dd', //显示格式
locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
onClose: () => print("----- onClose -----"),
onCancel: () => print('onCancel'),
onChange: (dateTime, List<int> index) { //改变的时候
setState(() {
_nowDate = dateTime;
});
},
onConfirm: (dateTime, List<int> index) { //确定的时候
setState(() {
_nowDate = dateTime;
});
},
);
}

效果图:

完整代码如下:

import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart'; class CupertinoTimePage extends StatefulWidget {
CupertinoTimePage({Key key}) : super(key: key); @override
_CupertinoTimePageState createState() => _CupertinoTimePageState();
} class _CupertinoTimePageState extends State<CupertinoTimePage> {
DateTime _nowDate = DateTime.now(); //当前日期
TimeOfDay _nowTime = TimeOfDay.now(); //当前时间 //调起flutter_cupertino_date_picker选择器
_cupertinoPicker(){
DatePicker.showDatePicker(
context,
pickerTheme: DateTimePickerTheme(
showTitle: true,
confirm: Text('确定', style: TextStyle(color: Colors.red)),
cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
),
minDateTime: DateTime.parse('2010-05-12'), //起始日期
maxDateTime: DateTime.parse('2021-11-25'), //终止日期
initialDateTime: _nowDate, //当前日期
dateFormat: 'yyyy-MMMM-dd', //显示格式
locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
onClose: () => print("----- onClose -----"),
onCancel: () => print('onCancel'),
onChange: (dateTime, List<int> index) { //改变的时候
setState(() {
_nowDate = dateTime;
});
},
onConfirm: (dateTime, List<int> index) { //确定的时候
setState(() {
_nowDate = dateTime;
});
},
);
} @override
Widget build(BuildContext context) {
var _date = formatDate(_nowDate, [yyyy, "-", mm, "-", dd]);return Scaffold(
appBar: AppBar(title: Text("第三方IOS时间选择器演示页面")),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: _cupertinoPicker,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("${_date}"),
Icon(Icons.arrow_drop_down)
],
),
),
]
),
]
)
);
}
}

2、datetime_picker_bottom_sheet

地址:https://github.com/dylanwuzh/flutter-cupertino-date-picker/blob/master/example/lib/datetime_picker_bottom_sheet.dart

调起datetime_picker_bottom选择器
//调起datetime_picker_bottom选择器
_cupertinoDateTimePicker(){
DatePicker.showDatePicker(
context,
minDateTime: DateTime.parse('2010-05-12'), //起始日期
maxDateTime: DateTime.parse('2021-11-25'), //终止日期
initialDateTime: DateTime.parse(formatDate(_selectedDateTime, [yyyy, "-", mm, "-", "dd", " ", HH, ":", nn, ":", ss])), //当前日期时间
dateFormat: "yyyy年M月d日 EEE,H时:m分", //显示格式
locale: DateTimePickerLocale.zh_cn, //语言
pickerTheme: DateTimePickerTheme(
showTitle: true,
),
pickerMode: DateTimePickerMode.datetime, // show TimePicker
onCancel: () {
debugPrint('onCancel');
},
onChange: (dateTime, List<int> index) {
setState(() {
_nowDate = dateTime;
});
},
onConfirm: (dateTime, List<int> index) {
setState(() {
_nowDate = dateTime;
});
},
);
}

效果图:

完整代码:

import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart'; class CupertinoTimePage extends StatefulWidget {
CupertinoTimePage({Key key}) : super(key: key); @override
_CupertinoTimePageState createState() => _CupertinoTimePageState();
} class _CupertinoTimePageState extends State<CupertinoTimePage> {
DateTime _nowDate = DateTime.now(); //当前日期
DateTime _nowDateTime = DateTime.parse(formatDate(DateTime.now(), [yyyy, "-", mm, "-", "dd", " ", HH, ":", nn, ":", ss])); //当前日期时间 //调起date_picker_bottom选择器
_cupertinoPicker(){
DatePicker.showDatePicker(
context,
pickerTheme: DateTimePickerTheme(
showTitle: true,
confirm: Text('确定', style: TextStyle(color: Colors.red)),
cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
),
minDateTime: DateTime.parse('2010-05-12'), //起始日期
maxDateTime: DateTime.parse('2021-11-25'), //终止日期
initialDateTime: _nowDate, //当前日期
dateFormat: 'yyyy-MMMM-dd', //显示格式
locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
onClose: () => print("----- onClose -----"),
onCancel: () => print('onCancel'),
onChange: (dateTime, List<int> index) { //改变的时候
setState(() {
_nowDate = dateTime;
});
},
onConfirm: (dateTime, List<int> index) { //确定的时候
setState(() {
_nowDate = dateTime;
});
},
);
} //调起datetime_picker_bottom选择器
_cupertinoDateTimePicker(){
DatePicker.showDatePicker(
context,
minDateTime: DateTime.parse('2010-05-12'), //起始日期
maxDateTime: DateTime.parse('2021-11-25'), //终止日期
//initialDateTime: DateTime.parse(formatDate(_selectedDateTime, [yyyy, "-", mm, "-", "dd", " ", HH, ":", nn, ":", ss])),
initialDateTime: _nowDateTime, //当前日期时间
dateFormat: "yyyy年M月d日 EEE,H时:m分", //显示格式
locale: DateTimePickerLocale.zh_cn, //语言
pickerTheme: DateTimePickerTheme(
showTitle: true,
),
pickerMode: DateTimePickerMode.datetime, // show TimePicker
onCancel: () {
debugPrint('onCancel');
},
onChange: (dateTime, List<int> index) {
setState(() {
_nowDate = dateTime;
});
},
onConfirm: (dateTime, List<int> index) {
setState(() {
_nowDate = dateTime;
});
},
);
} @override
Widget build(BuildContext context) {
var _date = formatDate(_nowDate, [yyyy, "-", mm, "-", dd]);
var _datetime = formatDate(_nowDate,[yyyy, "-", mm, "-", dd, " ", HH, ":", nn]);
return Scaffold(
appBar: AppBar(title: Text("第三方IOS时间选择器演示页面")),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: _cupertinoPicker,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("${_date}"),
Icon(Icons.arrow_drop_down)
],
),
),
]
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: _cupertinoDateTimePicker,
child: Row(
children: <Widget>[
Text('${_datetime}'),
Icon(Icons.arrow_drop_down)
],
),
)
],
)
]
)
);
}
}

Flutter中的日期插件date_format 中文 国际化 及flutter_cupertino_date_picker的更多相关文章

  1. (转)jQuery Mobile 移动开发中的日期插件Mobiscroll 2.3 使用说明

    (原)http://www.cnblogs.com/hxling/archive/2012/12/12/2814207.html jQuery Mobile 移动开发中的日期插件Mobiscroll ...

  2. Flutter中的日期、格式化日期、日期选择器组件

    Flutter中的日期和时间戳 //獲取當前日期 DateTime _nowDate = DateTime.now(); print(_nowDate);//2019-10-29 10:57:20.3 ...

  3. jQuery Mobile 移动开发中的日期插件Mobiscroll使用说明

    近期在移动方面的开发,使用jQuery Mobile ,移动方面的插件不如Web 方面的插件多,选择的更少,有一些需要自己去封装,但功力尚不足啊. 日期插件JQM也提供了内置的,但样式方面不好看,只好 ...

  4. boostrap 日期插件(带中文显示)

    不知道大家用什么样的日期插件,我最近用了bootstrap插件,整理了下,分享给大家,第四部分是我找的插件源码,可以省去大家的找的时间,按1-3的步骤用就好了,有些样式上的小问题就自己调一调: (1) ...

  5. Bootstrap日期插件中文实现

    Bootstrap的相关JS和CSS直接跳过. <script type="text/javascript" src="static/js/jquery-1.9.1 ...

  6. 日期插件My97DatePicker

    因为项目中需要选中日期,所以就找到了My97DatePicker这个插件,用法非常的简单,但是因为各个公司的要求不同,我们公司使用js拼代码,然后渲染到页面上的,所以遇到了一点问题… 1.My97Da ...

  7. Atitit.国际化中的日期与钱符号问题

    Atitit.国际化中的日期与钱符号问题 1. 用户名注册的问题 1 1.1. 不能限制用户名长度与特殊符号 1 2. 2.8月7号未必总写成8/7,有时也用7/8 2 3. 5.$未必总是指美元 3 ...

  8. Jquery中日期插件jquery.datepick的使用

    jsp的代码: <%@ page language="java" contentType="text/html; charset=UTF-8" pageE ...

  9. 在eclipse中安装properties插件PropertiesEditor及设置(附图),ASCII码转换成中文

    在eclipse中安装properties插件PropertiesEditor及设置(附图),ASCII码转换成中文安装成功后ASCII还是不能转换成中文的,原因是设置里面没有把编码设置为utf8的, ...

随机推荐

  1. codevs:1792分解质因数:编写一个把整数N分解为质因数乘积的程序。

    #include<iostream>#include<cstdio>using namespace std;int main(){ int i=2,n; scanf(" ...

  2. Note_4.9

    2019/4/9 奇奇怪怪的笔记 关于代码,基本上是现写的,可能连编译都过不了 因为是简单算法场,所以就很不走心了昂,/小纠结 图论相关  最小生成树 prim,kruskal 最小生成树的切割性质 ...

  3. 模板 - 数据结构 - ST表/SparseTable

    SparseTable,俗称ST表,其功能,就是静态的RMQ(区间最值查询)问题的解决.注意传入查询的时候两个参数的合法性,或者可以进行一次全部初始化来使得越界值不产生负面影响.不过访问越界是写程序的 ...

  4. 蚂蚁金服财富技术部,诚招Java研发工程师。校招内推!!!

    蚂蚁金服财富技术部,诚招Java研发工程师. 团队是蚂蚁金服财富技术部核心团队,支持亿级互联网交易清算,在这里不仅能学习到先进的互联网技术,也能了解许多终身受益的金融知识. 内推对象 2020届毕业生 ...

  5. Tuxedo 介绍

    快速阅读 介绍Tuxedo,以及webLogic两个中间件,都是oracle旗下的产品 ,现在各银行系统用的最多.因为有部分项目涉及,所以有必须弄清楚,明白 . 什么是Tuxedo 官方介绍:http ...

  6. 2018-2019-2 网络对抗技术 20165322 Exp8 Web基础

    2018-2019-2 网络对抗技术 20165322 Exp8 Web基础 目录 实验原理 实验内容与步骤 Web前端HTML Web前端javascipt Web后端:MySQL基础:正常安装.启 ...

  7. Thingsboard 重新启动docker-compose容器基础数据存在的问题

    在重启了thingsboard的容器后,想再次重新启动容器,发现已经出现了错误 查看posttres中,持久化的地址是tb-node/postgres中 再查看相应的文件夹 删除以上log和postg ...

  8. Understanding Action Filters (C#) 可以用来做权限检查

    比如需要操作某一张表league的数据,multi-tenancy的模式,每一行数据都有一个租户id的字段. 那么在api调用操作的时候,我们需要检查league的id,是否和当前用户所属的租户信息一 ...

  9. 优化Unity游戏项目的脚本(下)

    金秋9月,我们祝所有的老师们:教师节快乐 ! 今天,我们继续分享来自捷克的开发工程师Ondřej Kofroň,分享C#脚本的一系列优化方法. 在优化Unity游戏项目的脚本(上)中,我们介绍了如何查 ...

  10. R Shiny app | 交互式网页开发

    网页开发,尤其是交互式动态网页的开发,是有一定门槛的,如果你有一定的R基础,又不想过深的接触PHP和MySQL,那R的shiny就是一个不错的选择. 现在R shiny配合R在统计分析上的优势,可以做 ...