我想一起显示日期和时间选择器,但我认为没有任何小部件或库在 flutter 中提供此功能。 有什么建议或解决方案吗?
如果您不想添加额外的软件包,请组合
showDatePicker
和 showTimePicker
。
import 'package: flutter/material.dart';
Future<DateTime?> showDateTimePicker({
required BuildContext context,
DateTime? initialDate,
DateTime? firstDate,
DateTime? lastDate,
}) async {
initialDate ??= DateTime.now();
firstDate ??= initialDate.subtract(const Duration(days: 365 * 100));
lastDate ??= firstDate.add(const Duration(days: 365 * 200));
final DateTime? selectedDate = await showDatePicker(
context: context,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
);
if (selectedDate == null) return null;
if (!context.mounted) return selectedDate;
final TimeOfDay? selectedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(selectedDate),
);
return selectedTime == null
? selectedDate
: DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
}
尝试
flutter_datetime_picker
这里希望对你有帮助。
在此包中,您需要选择日期和时间。
date_time_picker
套餐
Updated Answer:
flutter_cupertino_datetime_picker
并根据需要设置日期格式
ElevatedButton(
onPressed: () {
dateTimePickerWidget(context);
},
child: Text('Pick Date-Time'),
),
dateTimePicker 的方法:
dateTimePickerWidget(BuildContext context) {
return DatePicker.showDatePicker(
context,
dateFormat: 'dd MMMM yyyy HH:mm',
initialDateTime: DateTime.now(),
minDateTime: DateTime(2000),
maxDateTime: DateTime(3000),
onMonthChangeStartWithFirstDate: true,
onConfirm: (dateTime, List<int> index) {
DateTime selectdate = dateTime;
final selIOS = DateFormat('dd-MMM-yyyy - HH:mm').format(selectdate);
print(selIOS);
},
);
}
您的输出:
16-Mar-2022 - 12:28
有一个包裹,也是
null safety
。
TextButton(
onPressed: () {
DatePicker.showDatePicker(context,
showTitleActions: true,
minTime: DateTime(2019, 3, 5),
maxTime: DateTime(2022, 1, 1), onChanged: (date) {
}, onConfirm: (date) {
print('Confirmed $date');
}, currentTime: DateTime.now(), locale: LocaleType.it);
},
child: Text(
'Show Datetime picker (italian)',
style: TextStyle(color: Colors.blue),
));
您可以使用此代码
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2101),
).then((selectedDate) {
// After selecting the date, display the time picker.
if (selectedDate != null) {
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((selectedTime) {
// Handle the selected date and time here.
if (selectedTime != null) {
DateTime selectedDateTime = DateTime(
selectedDate.year,
selectedDate.month,
selectedDate.day,
selectedTime.hour,
selectedTime.minute,
);
print(selectedDateTime); // You can use the selectedDateTime as needed.
}
});
}
});