dart 如何在Flutter中使用时间和日期选择器?

lsmd5eda  于 2023-04-27  发布在  Flutter
关注(0)|答案(3)|浏览(154)

我想显示日期和时间选择器在一起,但我认为没有任何部件或库提供此功能在Flutter。任何建议或解决方案?

ogsagwnx

ogsagwnx1#

试试**flutter_datetime_picker**here希望对你有帮助。
在此包中,您希望同时选择日期和时间。
也可以尝试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

Widget -〉x1c 0d1x的结果屏幕
DateTimePicker的结果屏幕-〉

eblbsuwk

eblbsuwk2#

有一个package,它也是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),
));
qij5mzcb

qij5mzcb3#

如果你不想添加额外的包,可以合并showDatePickershowTimePicker

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

相关问题