Material风格的日历选择器
showDatePicker
showDatePicker
是 flutter 封装的显示日期选择器的一个函数调用,其构造函数:
Future<DateTime?> showDatePicker({
required BuildContext context,
required DateTime initialDate,//初始化选中的日期
required DateTime firstDate,//可选的最早日期
required DateTime lastDate,//可选的最晚日期
DateTime? currentDate,//当前时间
DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar,// 用户是否只能从日历网格中选择日期
SelectableDayPredicate? selectableDayPredicate,
String? helpText,//select time 改写
String? cancelText,//自定义取消文本
String? confirmText,//自定义确定文本
Locale? locale,//设置所支持的语言为中文
bool useRootNavigator = true,
RouteSettings? routeSettings,
TextDirection? textDirection,
TransitionBuilder? builder,//修改颜色等
DatePickerMode initialDatePickerMode = DatePickerMode.day,//day:初始化显示天,year:初始化先选择年
String? errorFormatText,
String? errorInvalidText,
String? fieldHintText,
String? fieldLabelText,
TextInputType? keyboardType,
Offset? anchorPoint,
})
Future 是一个异步类型,因此 showDatePicker
是一个异步方法。
例子:
import 'package:flutter/material.dart';
class DatePickerPage2 extends StatefulWidget {
const DatePickerPage2({Key? key}) : super(key: key);
@override
State<DatePickerPage2> createState() => _DatePickerPage2State();
}
class _DatePickerPage2State extends State<DatePickerPage2> {
DateTime? _selectDateTime;
void _showDatePicker() async{
var result = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2021),
lastDate: DateTime(2030),
initialEntryMode: DatePickerEntryMode.calendarOnly,
helpText: '选择日期',
cancelText: '取消',
confirmText: '确定',
initialDatePickerMode: DatePickerMode.day,
builder: (context, Widget? child){
return Theme(
data: ThemeData(
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: Colors.red
)
),
colorScheme: const ColorScheme.light(
primary: Colors.red,
onPrimary: Colors.white
),
),
child: child!,
);
}
);
setState(() {
_selectDateTime = result;
print(_selectDateTime);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:const Text('日期选择器'),),
body: Center(
child: Column(
children: [
Container(
padding:const EdgeInsets.all(30),
child: Text(_selectDateTime != null ? _selectDateTime.toString():'未选择时间'),
),
ElevatedButton(
onPressed: (){_showDatePicker();},
child: const Text('showDatePicker',)
)
],
),
),
);
}
}
showTimePicker
构造函数:
Future<TimeOfDay?> showTimePicker({
required BuildContext context,
required TimeOfDay initialTime,//初始时间
TransitionBuilder? builder,
bool useRootNavigator = true,
TimePickerEntryMode initialEntryMode = TimePickerEntryMode.dial,
String? cancelText,
String? confirmText,
String? helpText,
String? errorInvalidText,//输入错误提示
String? hourLabelText,//小时文本
String? minuteLabelText,//分钟文本
RouteSettings? routeSettings,
EntryModeChangeCallback? onEntryModeChanged,
Offset? anchorPoint,
})
例子:
import 'package:flutter/material.dart';
class DatePickerPage2 extends StatefulWidget {
const DatePickerPage2({Key? key}) : super(key: key);
@override
State<DatePickerPage2> createState() => _DatePickerPage2State();
}
class _DatePickerPage2State extends State<DatePickerPage2> {
//showTimePicker
String? _selectDateTime2;
Future<void> _showTimePicker() async{
final TimeOfDay? result = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(DateTime.now()),
helpText: '选择日期',
cancelText: '取消',
confirmText: '确定',
builder: (context, Widget? child){
return Theme(
data: ThemeData(
timePickerTheme: TimePickerThemeData(
backgroundColor: Colors.amber,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
hourMinuteShape: const CircleBorder(),
),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
foregroundColor: Colors.red
)
),
colorScheme: const ColorScheme.light(
primary: Colors.red,
onPrimary: Colors.white
),
),
child: child!,
);
}
);
if(result != null){
setState(() {
_selectDateTime2 = result.format(context);
print(_selectDateTime2);
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:const Text('日期选择器'),),
body: Center(
child: Column(
children: [
Container(
padding:const EdgeInsets.all(30),
child: Text(_selectDateTime2 != null ? _selectDateTime2!:'未选择时间'),
),
ElevatedButton(
onPressed: (){_showTimePicker();},
child: const Text('showTimePicker',)
),
],
),
),
);
}
}
效果:
showTimePicker
24小时制设置。
//showTimePicker 24小时制
String? _selectDateTime3;
Future<void> _showTimePicker3() async{
final TimeOfDay? result = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
builder: (context , child){
return MediaQuery(
data: MediaQuery.of(context).copyWith(
alwaysUse24HourFormat: true
),
child: child!,
);
}
);
if(result != null){
setState(() {
_selectDateTime3 = result.format(context);
print(_selectDateTime3);
});
}
}
showDateRangePicker
showDateRangePicker
是Flutter提供的一个选择一段日期的日历选择器。其构造函数:
Future<DateTimeRange?> showDateRangePicker({
required BuildContext context,
DateTimeRange? initialDateRange,//初始日期范围
required DateTime firstDate,//日历开始日期
required DateTime lastDate,//日历结束日期
DateTime? currentDate,//当前日期
DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar,//DatePickerEntryMode 日历弹框样式 calendar: 默认显示日历,可切换成输入模式,input:默认显示输入模式,可切换到日历,calendarOnly:只显示日历,inputOnly:只显示输入模式
String? helpText,//左上角提示语
String? cancelText,
String? confirmText,
String? saveText,//保存按钮文本
String? errorFormatText,//格式错误时下方提示
String? errorInvalidText,//输入了不在 first 与 last 之间的日期提示语
String? errorInvalidRangeText,//输入日期范围不合法
String? fieldStartHintText,//开始日期 输入框默认提示语
String? fieldEndHintText,//结束日期 输入框默认提示语
String? fieldStartLabelText,//开始日期 输入框上方提示语
String? fieldEndLabelText,//结束日期 输入框上方提示语
Locale? locale,//多语言设置
bool useRootNavigator = true,
RouteSettings? routeSettings,
TextDirection? textDirection,
TransitionBuilder? builder,
Offset? anchorPoint,
})
例子:
import 'package:flutter/material.dart';
class DatePickerPage3 extends StatefulWidget {
const DatePickerPage3({Key? key}) : super(key: key);
@override
State<DatePickerPage3> createState() => _DatePickerPage3State();
}
class _DatePickerPage3State extends State<DatePickerPage3> {
String? _selectDateTimeRange;
Future<DateTimeRange?> _showRangeDatePickerForDay() async{
final DateTimeRange? result = await showDateRangePicker(
context: context,
firstDate: DateTime(2022,1,1),
lastDate: DateTime(2026,12,12),
currentDate: DateTime.now(),
initialDateRange: DateTimeRange(
start: DateTime.now().subtract(const Duration(days: 5)),
end: DateTime.now().add(const Duration(days: 5))
),
initialEntryMode: DatePickerEntryMode.calendar,
helpText: '请选择日期区间',
cancelText: '取消',
confirmText: '确定',
saveText: '完成',
errorFormatText: '输入格式有错误',
errorInvalidRangeText: '开始日期不可以在结束之后',
errorInvalidText: '输入不合法',
builder: (context,child){
return Theme(
data: ThemeData(primarySwatch: Colors.amber),
child: child!
);
}
);
setState(() {
_selectDateTimeRange = result.toString();
print(_selectDateTimeRange);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('showDateRangePicker'),),
body: Center(
child: Column(
children: [
Container(
padding:const EdgeInsets.all(30),
child: Text(_selectDateTimeRange != null ? _selectDateTimeRange!:'未选择时间'),
),
ElevatedButton(
onPressed: (){_showRangeDatePickerForDay();},
child: const Text('showTimePicker',)
),
],
),
),
);
}
}
效果: