Flutter日期时间选择器插件date_time_picker_widget的使用
Flutter日期时间选择器插件date_time_picker_widget
的使用
date_time_picker_widget
是一个用于在Flutter应用中选择日期和时间的新UI设计插件。本文将详细介绍如何在Flutter项目中集成并使用这个插件。
添加依赖
首先,在你的 pubspec.yaml
文件中添加以下依赖:
dependencies:
...
date_time_picker_widget: ^2.0.0
然后运行 flutter pub get
来安装该插件。
导入包
在你的Dart文件中导入该插件:
import 'package:date_time_picker_widget/date_time_picker_widget.dart';
示例代码
下面是一个完整的示例,展示了如何使用 DateTimePicker
小部件来选择日期和时间。
完整示例Demo
import 'package:date_time_picker_widget/date_time_picker_widget.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.from(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
),
home: const MyHomePage(title: 'Date Time Picker Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Color _color = Colors.blue;
String _d1 = '', _d2 = '';
String _t1 = '', _t2 = '';
bool _material3 = true;
@override
Widget build(BuildContext context) {
return Theme(
data: Theme.of(context).copyWith(
colorScheme: ColorScheme.fromSeed(
seedColor: _color,
primary: _color,
secondary: _color,
),
useMaterial3: _material3,
),
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SafeArea(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const SizedBox(height: 24),
CheckboxListTile(
value: _material3,
title: Text(
'Use Material 3',
style: Theme.of(context).textTheme.titleLarge,
),
onChanged: (value) {
setState(() {
_material3 = value ?? true;
});
},
),
const SizedBox(height: 24),
Text(
'Color Pallet',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 24),
_colorPallet(),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 24),
_dateTimePicker(),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 24),
_datePicker(),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 24),
_timePicker(),
const Divider(),
const SizedBox(height: 24),
_newDatetimePicker(),
],
),
),
),
),
),
);
}
Widget _newDatetimePicker(){
final dt = DateTime.now();
final dtMin = DateTime.now().add(const Duration(hours: 1, minutes: 0));
final dtMax = dtMin.add(const Duration(days: 4));
return Container(
child: DateTimePicker(
initialSelectedDate: dtMin,
startDate: dtMin,
endDate: dtMax,
startTime: dt,
endTime: dtMax,
timeInterval: const Duration(minutes: 15),
datePickerTitle: 'Pick your preferred date',
timePickerTitle: 'Pick your preferred time',
timeOutOfRangeError: 'Sorry shop is closed now',
is24h: false,
numberOfWeeksToDisplay: 1,
locale: 'es',
customStringWeekdays: const ['D', 'L', 'M', 'X', 'J', 'V', 'S'],
onDateChanged: (date) {
setState(() {
_d1 = DateFormat('dd MMM, yyyy').format(date);
});
},
onTimeChanged: (time) {
setState(() {
_t1 = DateFormat('hh:mm:ss aa').format(time);
});
},
),
);
}
Widget _dateTimePicker() {
final dt = DateTime.now();
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Date & Time Picker',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Date: $_d1 Time: $_t1',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 16),
DateTimePicker(
initialSelectedDate: dt,
startDate: dt.subtract(const Duration(days: 1)),
endDate: dt.add(const Duration(days: 60)),
startTime: DateTime(dt.year, dt.month, dt.day, 6),
endTime: DateTime(dt.year, dt.month, dt.day, 18),
timeInterval: const Duration(minutes: 15),
datePickerTitle: 'Pick your preferred date',
timePickerTitle: 'Pick your preferred time',
timeOutOfRangeError: 'Sorry shop is closed now',
is24h: false,
numberOfWeeksToDisplay: 4,
onDateChanged: (date) {
setState(() {
_d1 = DateFormat('dd MMM, yyyy').format(date);
});
},
onTimeChanged: (time) {
setState(() {
_t1 = DateFormat('hh:mm:ss aa').format(time);
});
},
)
],
);
}
Widget _datePicker() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Date Picker',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Date: $_d2',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 16),
DateTimePicker(
type: DateTimePickerType.Date,
onDateChanged: (date) {
setState(() {
_d2 = DateFormat('dd MMM, yyyy').format(date);
});
},
)
],
);
}
Widget _timePicker() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Time Picker',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Time: $_t2',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 16),
DateTimePicker(
type: DateTimePickerType.Time,
timeInterval: const Duration(minutes: 30),
onTimeChanged: (time) {
setState(() {
_t2 = DateFormat('hh:mm:ss aa').format(time);
});
},
)
],
);
}
Widget _colorPallet() {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
InkWell(
onTap: () {
setState(() {
_color = Colors.amber;
});
},
child: Container(
width: 24,
height: 24,
color: Colors.amber,
),
),
InkWell(
onTap: () {
setState(() {
_color = Colors.green;
});
},
child: Container(
width: 24,
height: 24,
color: Colors.green,
),
),
InkWell(
onTap: () {
setState(() {
_color = Colors.blue;
});
},
child: Container(
width: 24,
height: 24,
color: Colors.blue,
),
),
InkWell(
onTap: () {
setState(() {
_color = Colors.deepPurple;
});
},
child: Container(
width: 24,
height: 24,
color: Colors.deepPurple,
),
),
],
);
}
}
参数说明
type
: 可以设置为DateTimePickerType.Date
,DateTimePickerType.Time
, 或DateTimePickerType.Both
。initialSelectedDate
: 初始选中的日期。startDate
: 开始日期。endDate
: 结束日期。startTime
: 开始时间。endTime
: 结束时间。timeInterval
: 时间间隔,默认是15分钟。datePickerTitle
: 日期选择器标题。timePickerTitle
: 时间选择器标题。timeOutOfRangeError
: 时间超出范围时的错误提示。is24h
: 是否使用24小时制。locale
: 设置语言环境,例如'es'
表示西班牙语。customStringWeekdays
: 自定义星期几的显示名称。
通过上述步骤,你可以在Flutter应用中轻松实现日期和时间的选择功能。希望这个指南对你有所帮助!
更多关于Flutter日期时间选择器插件date_time_picker_widget的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter日期时间选择器插件date_time_picker_widget的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用date_time_picker_widget
插件的一个示例代码案例。首先,确保你已经在pubspec.yaml
文件中添加了该插件的依赖项:
dependencies:
flutter:
sdk: flutter
date_time_picker_widget: ^x.y.z # 请替换为最新版本号
然后,运行flutter pub get
来获取依赖项。
接下来,你可以在你的Flutter应用中使用DateTimePickerWidget
。以下是一个完整的示例,展示如何在Flutter应用中实现日期和时间选择器:
import 'package:flutter/material.dart';
import 'package:date_time_picker_widget/date_time_picker_widget.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'DateTimePickerWidget Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTime? selectedDateTime;
void _selectDateTime(BuildContext context) async {
final DateTimePickerResult result = await DateTimePickerWidget.showDateTimePicker(
context: context,
language: DateTimePickerLanguage.en,
initialDateTime: selectedDateTime ?? DateTime.now(),
dateFormat: "yyyy-MM-dd",
timeFormat: "HH:mm:ss",
title: "Select Date & Time",
is24HourFormat: true,
);
if (result.confirmed && result.dateTime != null) {
setState(() {
selectedDateTime = result.dateTime;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DateTimePickerWidget Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
selectedDateTime == null
? 'No date and time selected'
: 'Selected Date and Time: ${selectedDateTime!.toLocal()}',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () => _selectDateTime(context),
child: Text('Select Date & Time'),
),
],
),
),
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮,点击按钮时会显示一个日期和时间选择器。选择日期和时间后,选定的日期和时间会显示在页面上。
代码解释:
- 依赖项:在
pubspec.yaml
文件中添加date_time_picker_widget
依赖项。 - 主应用:
MyApp
类作为应用的入口点。 - 主页面:
MyHomePage
是一个有状态的组件,用于管理选中的日期和时间。 - 选择日期和时间:
_selectDateTime
方法使用DateTimePickerWidget.showDateTimePicker
显示日期和时间选择器,并将结果存储在selectedDateTime
变量中。 - UI:使用
Text
和ElevatedButton
组件来显示选中的日期和时间以及触发日期时间选择器的按钮。
希望这个示例能帮助你更好地了解如何在Flutter中使用date_time_picker_widget
插件。如果你有任何其他问题,欢迎继续提问!