Flutter 之 日期时间选择器(iOS 风格)(九十一)

2022-05-31  本文已影响0人  maskerII

CupertinoDatePicker、CupertinoTimerPicker 是 iOS 风格的 DatePickerView 和 TimePickerView 的日期时间选择器。

1. CupertinoTimerPicker

CupertinoDatePicker 定义

  CupertinoDatePicker({
    Key? key,
    this.mode = CupertinoDatePickerMode.dateAndTime,
    required this.onDateTimeChanged,
    DateTime? initialDateTime,
    this.minimumDate,
    this.maximumDate,
    this.minimumYear = 1,
    this.maximumYear,
    this.minuteInterval = 1,
    this.use24hFormat = false,
    this.dateOrder,
    this.backgroundColor,
  })

CupertinoDatePicker 属性

CupertinoDatePicker 属性 介绍
mode CupertinoDatePickerMode 日期选择器模式 ,time,date,dateAndTime, 默认dateAndTime
onDateTimeChanged @required 选中日期变化回调
initialDateTime 当前日期
minimumDate 最小可选日期
maximumDate 最大可选日期
minimumYear 最小年份
maximumYear 最大年份
minuteInterval 分钟间隔 initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
use24hFormat 是否使用24小时制
dateOrder 期选择器排序方式 默认年/月/日
backgroundColor 背景色

2. CupertinoDatePicker 实例

注意:取消、确认按钮是自己绘制的,不是cupertinoDatePicker提供的

示例1 CupertinoDatePickerMode.date

        final CupertinoDatePicker cupertinoDatePicker = CupertinoDatePicker(
          mode: CupertinoDatePickerMode
              .date, // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
          initialDateTime: DateTime.now(), // 初始化日期
          minimumDate: DateTime(2021, 10, 10), // 最小可选日期
          maximumDate: DateTime(2023, 12, 22), // 最大可选日期
          minimumYear: 2020, // 最小年份
          maximumYear: 2025, // 最大年份
          minuteInterval:
              1, // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
          use24hFormat: true, // 是否使用24小时制
          dateOrder: DatePickerDateOrder.dmy, // 日期选择器排序方式 默认年/月/日
          backgroundColor: Colors.white,
          // 选中日期变化回调
          onDateTimeChanged: (dateTime) {
            _chooseDateTime = dateTime;
          },
        );
image.png

示例2 CupertinoDatePickerMode.dateAndTime

        final CupertinoDatePicker cupertinoDatePicker = CupertinoDatePicker(
          mode: CupertinoDatePickerMode
              .dateAndTime, // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
          initialDateTime: DateTime.now(), // 初始化日期
          minimumDate: DateTime(2021, 10, 10), // 最小可选日期
          maximumDate: DateTime(2023, 12, 22), // 最大可选日期
          minimumYear: 2020, // 最小年份
          maximumYear: 2025, // 最大年份
          minuteInterval:
              1, // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
          use24hFormat: false, // 是否使用24小时制
          dateOrder: DatePickerDateOrder.ymd, // 日期选择器排序方式 默认年/月/日
          backgroundColor: Colors.white,
          // 选中日期变化回调
          onDateTimeChanged: (dateTime) {
            _chooseDateTime = dateTime;
          },
        );
image.png

示例3 CupertinoDatePickerMode.time

        final CupertinoDatePicker cupertinoDatePicker = CupertinoDatePicker(
          mode: CupertinoDatePickerMode
              .time, // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
          initialDateTime: DateTime.now(), // 初始化日期
          minimumDate: DateTime(2021, 10, 10), // 最小可选日期
          maximumDate: DateTime(2023, 12, 22), // 最大可选日期
          minimumYear: 2020, // 最小年份
          maximumYear: 2025, // 最大年份
          minuteInterval:
              1, // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
          use24hFormat: false, // 是否使用24小时制
          dateOrder: DatePickerDateOrder.ymd, // 日期选择器排序方式 默认年/月/日
          backgroundColor: Colors.white,
          // 选中日期变化回调
          onDateTimeChanged: (dateTime) {
            _chooseDateTime = dateTime;
          },
        );
image.png

3. CupertinoTimerPicker

CupertinoTimerPicker 定义

  CupertinoTimerPicker({
    Key? key,
    this.mode = CupertinoTimerPickerMode.hms,
    this.initialTimerDuration = Duration.zero,
    this.minuteInterval = 1,
    this.secondInterval = 1,
    this.alignment = Alignment.center,
    this.backgroundColor,
    required this.onTimerDurationChanged,
  }) 

CupertinoTimerPicker 属性

CupertinoTimerPicker 属性 介绍
mode CupertinoTimerPickerMode,时间选择器模式 ,hm,ms,hms,默认hms
initialTimerDuration 初始化时间
minuteInterval 分钟间隔
secondInterval 秒钟间隔
alignment 对齐方式
backgroundColor 背景色
onTimerDurationChanged @required ValueChanged<Duration> onTimerDurationChanged,选中时间变化回调

4. CupertinoTimerPicker 实例

示例1 CupertinoTimerPickerMode.hms

        final cupertinoTimerPicker = CupertinoTimerPicker(
          mode: CupertinoTimerPickerMode.hms, // 时间选择器模式
          initialTimerDuration: Duration(hours: 1), // 初始化时间
          minuteInterval: 5, // 分钟间隔
          secondInterval: 20, // 秒钟间隔
          alignment: Alignment.center, // 对齐方式
          backgroundColor: Colors.white, // 背景色
          // 选中时间变化回调
          onTimerDurationChanged: (dur) {
            chooseDuration = dur;
          },
        );
image.png

示例2 CupertinoTimerPickerMode.ms

        final cupertinoTimerPicker = CupertinoTimerPicker(
          mode: CupertinoTimerPickerMode.ms, // 时间选择器模式
          initialTimerDuration: Duration(minutes: 10), // 初始化时间
          minuteInterval: 5, // 分钟间隔
          secondInterval: 20, // 秒钟间隔
          alignment: Alignment.center, // 对齐方式
          backgroundColor: Colors.white, // 背景色
          // 选中时间变化回调
          onTimerDurationChanged: (dur) {
            chooseDuration = dur;
          },
        );
image.png

示例3 CupertinoTimerPickerMode.hm

        final cupertinoTimerPicker = CupertinoTimerPicker(
          mode: CupertinoTimerPickerMode.hm, // 时间选择器模式
          initialTimerDuration: Duration(minutes: 20), // 初始化时间
          minuteInterval: 5, // 分钟间隔
          secondInterval: 20, // 秒钟间隔
          alignment: Alignment.center, // 对齐方式
          backgroundColor: Colors.white, // 背景色
          // 选中时间变化回调
          onTimerDurationChanged: (dur) {
            chooseDuration = dur;
          },
        );
image.png

5. flutter_cupertino_datetime_picker 三方库

dependencies:
  flutter_cupertino_datetime_picker: ^3.0.0

示例1 - DateTimePickerMode.time

  _showDatePickerForTime(BuildContext context){
    iOSDatePicker.DatePicker.showDatePicker(
      context, // 上下文
      pickerMode: iOSDatePicker.DateTimePickerMode.time, // 选择器模式
      dateFormat: "HH:mm:ss", // 日期格式
      minuteDivider: 5, // 分钟间隔
      // 选择回调
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        print("选择 $dateTime");
      },
      // 取消回调
      onCancel: () {},
      // 关闭回调
      onClose: () {},
      // 选中时间发生变化 回调
      onChange: (datetime, selectedIndex) {},
    );
  }
image.png

示例2 - DateTimePickerMode.datetime

  _showDatePickerForDateTime(BuildContext context){
    iOSDatePicker.DatePicker.showDatePicker(
      context,
      pickerMode: iOSDatePicker.DateTimePickerMode.datetime,
      minDateTime: DateTime(2022, 1, 10),
      maxDateTime: DateTime(2022, 10, 10),
      dateFormat: "yyyy|MM|dd HH:mm",
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        print("选择 $dateTime");
      },
      onCancel: () {},
      onClose: () {},
      onChange: (datetime, selectedIndex) {},
    );
  }
image.png

示例3 - DateTimePickerMode.date

  _showDatePickerForDate(BuildContext context) {
    iOSDatePicker.DatePicker.showDatePicker(
      context,
      pickerMode: iOSDatePicker.DateTimePickerMode.date,
      minDateTime: DateTime(2022, 1, 10),
      maxDateTime: DateTime(2022, 10, 10),
      initialDateTime: DateTime.now(),
      dateFormat: "MM|dd,yyyy年",
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        print("选择 $dateTime");
      },
      onCancel: () {},
      onClose: () {},
      onChange: (datetime, selectedIndex) {},
    );
  }
image.png

6. Demo

MSCupertinoDateAndTimePickerDemo


class MSCupertinoDateAndTimePickerDemo extends StatelessWidget {
  MSCupertinoDateAndTimePickerDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("MSCupertinoDateAndTimePickerDemo")),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () async {
                  DateTime? dateTime =
                      await _showCupertinoDatePickerForDate(context);
                  if (dateTime == null) {
                    print("取消选择");
                  } else {
                    print("选择 $dateTime");
                  }
                },
                child: Text("CupertinoDatePicker-Date"),
              ),
              ElevatedButton(
                onPressed: () async {
                  DateTime? dateTime =
                      await _showCupertinoDatePickerForDateAndTime(context);
                  if (dateTime == null) {
                    print("取消选择");
                  } else {
                    print("选择 $dateTime");
                  }
                },
                child: Text("CupertinoDatePicker-DateTime"),
              ),
              ElevatedButton(
                onPressed: () async {
                  DateTime? dateTime =
                      await _showCupertinoDatePickerForTime(context);
                  if (dateTime == null) {
                    print("取消选择");
                  } else {
                    print("选择 $dateTime");
                  }
                },
                child: Text("CupertinoDatePicker-Time"),
              ),
              ElevatedButton(
                onPressed: () async {
                  Duration? dur = await _showCupertinoTimePickerForHMS(context);
                  if (dur == null) {
                    print("取消选择");
                  } else {
                    print("选择 $dur");
                  }
                },
                child: Text("CupertinoTimerPicker-HMS"),
              ),
              ElevatedButton(
                onPressed: () async {
                  Duration? dur = await _showCupertinoTimePickerForMS(context);
                  if (dur == null) {
                    print("取消选择");
                  } else {
                    print("选择 $dur");
                  }
                },
                child: Text("CupertinoTimerPicker-MS"),
              ),
              ElevatedButton(
                onPressed: () async {
                  Duration? dur = await _showCupertinoTimePickerForHM(context);
                  if (dur == null) {
                    print("取消选择");
                  } else {
                    print("选择 $dur");
                  }
                },
                child: Text("CupertinoTimerPicker-HM"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // CupertinoDatePicker
  DateTime? chooseDateTime;
  _getActions(BuildContext context) {
    final Widget actions = Container(
      alignment: AlignmentDirectional.centerEnd,
      constraints: const BoxConstraints(minHeight: 52.0),
      padding: const EdgeInsets.symmetric(horizontal: 8),
      color: Colors.white,
      child: OverflowBar(
        alignment: MainAxisAlignment.spaceBetween,
        spacing: 8,
        children: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text(
              "取消",
              textScaleFactor: 1.2,
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(chooseDateTime);
            },
            child: Text(
              "确定",
              textScaleFactor: 1.2,
            ),
          ),
        ],
      ),
    );
    return actions;
  }

  Future<DateTime?> _showCupertinoDatePickerForDate(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (context) {
        final CupertinoDatePicker cupertinoDatePicker = CupertinoDatePicker(
          mode: CupertinoDatePickerMode
              .date, // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
          initialDateTime: DateTime.now(), // 初始化日期
          minimumDate: DateTime(2021, 10, 10), // 最小可选日期
          maximumDate: DateTime(2023, 12, 22), // 最大可选日期
          minimumYear: 2020, // 最小年份
          maximumYear: 2025, // 最大年份
          minuteInterval:
              1, // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
          use24hFormat: true, // 是否使用24小时制
          dateOrder: DatePickerDateOrder.dmy, // 日期选择器排序方式 默认年/月/日
          backgroundColor: Colors.white,
          // 选中日期变化回调
          onDateTimeChanged: (dateTime) {
            chooseDateTime = dateTime;
          },
        );

        // 初始化chooseDateTime
        chooseDateTime = cupertinoDatePicker.initialDateTime;
        return AnimatedContainer(
          duration: Duration(microseconds: 200),
          height: 300,
          width: double.infinity,
          child: Column(
            children: [
              _getActions(context),
              Expanded(
                child: cupertinoDatePicker,
              ),
            ],
          ),
        );
      },
    );
  }

  Future<DateTime?> _showCupertinoDatePickerForDateAndTime(
      BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (context) {
        final CupertinoDatePicker cupertinoDatePicker = CupertinoDatePicker(
          mode: CupertinoDatePickerMode
              .dateAndTime, // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
          initialDateTime: DateTime.now(), // 初始化日期
          minimumDate: DateTime(2021, 10, 10), // 最小可选日期
          maximumDate: DateTime(2023, 12, 22), // 最大可选日期
          minimumYear: 2020, // 最小年份
          maximumYear: 2025, // 最大年份
          minuteInterval:
              1, // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
          use24hFormat: false, // 是否使用24小时制
          dateOrder: DatePickerDateOrder.ymd, // 日期选择器排序方式 默认年/月/日
          backgroundColor: Colors.white,
          // 选中日期变化回调
          onDateTimeChanged: (dateTime) {
            chooseDateTime = dateTime;
          },
        );

        // 初始化chooseDateTime
        chooseDateTime = cupertinoDatePicker.initialDateTime;

        return AnimatedContainer(
          duration: Duration(microseconds: 200),
          height: 300,
          width: double.infinity,
          child: Column(
            children: [
              _getActions(context),
              Expanded(
                child: cupertinoDatePicker,
              ),
            ],
          ),
        );
      },
    );
  }

  Future<DateTime?> _showCupertinoDatePickerForTime(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (context) {
        final CupertinoDatePicker cupertinoDatePicker = CupertinoDatePicker(
          mode: CupertinoDatePickerMode
              .time, // 日期选择器模式 `time`,`date`,`dateAndTime`, 默认`dateAndTime`
          initialDateTime: DateTime.now(), // 初始化日期
          minimumDate: DateTime(2021, 10, 10), // 最小可选日期
          maximumDate: DateTime(2023, 12, 22), // 最大可选日期
          minimumYear: 2020, // 最小年份
          maximumYear: 2025, // 最大年份
          minuteInterval:
              1, // 分钟间隔  initialDateTime.minute 必须可以整除 minuteInterval 必须是 60 的整数因子
          use24hFormat: false, // 是否使用24小时制
          dateOrder: DatePickerDateOrder.ymd, // 日期选择器排序方式 默认年/月/日
          backgroundColor: Colors.white,
          // 选中日期变化回调
          onDateTimeChanged: (dateTime) {
            chooseDateTime = dateTime;
          },
        );
        // 初始化chooseDateTime
        chooseDateTime = cupertinoDatePicker.initialDateTime;
        return AnimatedContainer(
          duration: Duration(microseconds: 200),
          height: 300,
          width: double.infinity,
          child: Column(
            children: [
              _getActions(context),
              Expanded(
                child: cupertinoDatePicker,
              ),
            ],
          ),
        );
      },
    );
  }

  // CupertinoTimerPicker
  Duration? chooseDuration;
  _getActions2(BuildContext context) {
    final Widget actions = Container(
      alignment: AlignmentDirectional.centerEnd,
      constraints: const BoxConstraints(minHeight: 52.0),
      padding: const EdgeInsets.symmetric(horizontal: 8),
      color: Colors.white,
      child: OverflowBar(
        alignment: MainAxisAlignment.spaceBetween,
        spacing: 8,
        children: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text(
              "取消",
              textScaleFactor: 1.2,
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(chooseDuration);
            },
            child: Text(
              "确定",
              textScaleFactor: 1.2,
            ),
          ),
        ],
      ),
    );
    return actions;
  }

  Future<Duration?> _showCupertinoTimePickerForHMS(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (context) {
        final cupertinoTimerPicker = CupertinoTimerPicker(
          mode: CupertinoTimerPickerMode.hms, // 时间选择器模式
          initialTimerDuration: Duration(hours: 1), // 初始化时间
          minuteInterval: 5, // 分钟间隔
          secondInterval: 20, // 秒钟间隔
          alignment: Alignment.center, // 对齐方式
          backgroundColor: Colors.white, // 背景色
          // 选中时间变化回调
          onTimerDurationChanged: (dur) {
            chooseDuration = dur;
          },
        );
        chooseDuration = cupertinoTimerPicker.initialTimerDuration;
        return AnimatedContainer(
          duration: Duration(microseconds: 200),
          height: 268,
          width: double.infinity,
          child: Container(
            color: Colors.white,
            child: Column(
              children: [
                _getActions2(context),
                Expanded(child: cupertinoTimerPicker),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<Duration?> _showCupertinoTimePickerForMS(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (context) {
        final cupertinoTimerPicker = CupertinoTimerPicker(
          mode: CupertinoTimerPickerMode.ms, // 时间选择器模式
          initialTimerDuration: Duration(minutes: 10), // 初始化时间
          minuteInterval: 5, // 分钟间隔
          secondInterval: 20, // 秒钟间隔
          alignment: Alignment.center, // 对齐方式
          backgroundColor: Colors.white, // 背景色
          // 选中时间变化回调
          onTimerDurationChanged: (dur) {
            chooseDuration = dur;
          },
        );
        chooseDuration = cupertinoTimerPicker.initialTimerDuration;
        return AnimatedContainer(
          duration: Duration(microseconds: 200),
          height: 268,
          width: double.infinity,
          child: Container(
            color: Colors.white,
            child: Column(
              children: [
                _getActions2(context),
                Expanded(child: cupertinoTimerPicker),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<Duration?> _showCupertinoTimePickerForHM(BuildContext context) {
    return showCupertinoModalPopup(
      context: context,
      builder: (context) {
        final cupertinoTimerPicker = CupertinoTimerPicker(
          mode: CupertinoTimerPickerMode.hm, // 时间选择器模式
          initialTimerDuration: Duration(minutes: 20), // 初始化时间
          minuteInterval: 5, // 分钟间隔
          secondInterval: 20, // 秒钟间隔
          alignment: Alignment.center, // 对齐方式
          backgroundColor: Colors.white, // 背景色
          // 选中时间变化回调
          onTimerDurationChanged: (dur) {
            chooseDuration = dur;
          },
        );
        chooseDuration = cupertinoTimerPicker.initialTimerDuration;
        return AnimatedContainer(
          duration: Duration(microseconds: 200),
          height: 268,
          width: double.infinity,
          child: Container(
            color: Colors.white,
            child: Column(
              children: [
                _getActions2(context),
                Expanded(child: cupertinoTimerPicker),
              ],
            ),
          ),
        );
      },
    );
  }
}

127.gif

三方库flutter_cupertino_datetime_picker Demo

import 'package:flutter/material.dart';

import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart'
    as iOSDatePicker;

class MSCupertinoDatetimePickerLibDemo extends StatelessWidget {
  const MSCupertinoDatetimePickerLibDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("三方日期选择库")),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () {
                  _showDatePickerForTime(context);
                },
                child: Text("DatePicker-Time"),
              ),
              ElevatedButton(
                onPressed: () {
                  _showDatePickerForDateTime(context);
                },
                child: Text("DatePicker-DateTime"),
              ),
              ElevatedButton(
                onPressed: () {
                  _showDatePickerForDate(context);
                },
                child: Text("DatePicker-Date"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _showDatePickerForTime(BuildContext context) {
    iOSDatePicker.DatePicker.showDatePicker(
      context, // 上下文
      pickerMode: iOSDatePicker.DateTimePickerMode.time, // 选择器模式
      dateFormat: "HH:mm:ss", // 日期格式
      minuteDivider: 5, // 分钟间隔
      // 选择回调
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        print("选择 $dateTime");
      },
      // 取消回调
      onCancel: () {},
      // 关闭回调
      onClose: () {},
      // 选中时间发生变化 回调
      onChange: (datetime, selectedIndex) {},
    );
  }

  _showDatePickerForDateTime(BuildContext context) {
    iOSDatePicker.DatePicker.showDatePicker(
      context,
      pickerMode: iOSDatePicker.DateTimePickerMode.datetime,
      minDateTime: DateTime(2022, 1, 10),
      maxDateTime: DateTime(2022, 10, 10),
      dateFormat: "yyyy|MM|dd HH:mm",
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        print("选择 $dateTime");
      },
      onCancel: () {},
      onClose: () {},
      onChange: (datetime, selectedIndex) {},
    );
  }

  _showDatePickerForDate(BuildContext context) {
    iOSDatePicker.DatePicker.showDatePicker(
      context,
      pickerMode: iOSDatePicker.DateTimePickerMode.date,
      minDateTime: DateTime(2022, 1, 10),
      maxDateTime: DateTime(2022, 10, 10),
      initialDateTime: DateTime.now(),
      dateFormat: "MM|dd,yyyy年",
      onConfirm: (DateTime dateTime, List<int> selectedIndex) {
        print("选择 $dateTime");
      },
      onCancel: () {},
      onClose: () {},
      onChange: (datetime, selectedIndex) {},
    );
  }
}

128.gif
上一篇下一篇

猜你喜欢

热点阅读