Flutter showDatePicker


简介

日期选择器的对话框

  • 返回为Futer,为用户关闭对话框时用户选择的日期。如果用户取消该对话框,则返回为null

基本用法

  • selectableDayPredicate可以传入自定义选择的天数。
  • 可选initialDatePickerMode参数可用于最初在年或月+日选择器模式中显示日期选择器。默认为月+日,且不能为空。
  • 可选locale参数可用于设置日期选择器的区域设置

实例演示

import 'dart:async';

import 'package:flutter/material.dart';

class ShowDatePickerDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ShowDatePickerState();
}

class _ShowDatePickerState extends State<ShowDatePickerDemo> {
  DateTime _date =  DateTime.now();
  TimeOfDay _time =  TimeOfDay.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: _date,
        firstDate: DateTime(2015, 8),
        lastDate: DateTime(2101));
    if (picked != null && picked != _date)
      print("data selectied :${_date.toString()}");
    setState(() {
      _date = picked;
    });

    if (picked == null) _date =  DateTime.now();
  }

  Future<void> _selectTime(BuildContext context) async {
    final TimeOfDay picked =
        await showTimePicker(context: context, initialTime: _time);
    if (picked != null && picked != _time)
      print("data selectied :${_time.toString()}");
    setState(() {
      _time = picked;
    });
    if (picked == null) _time =  TimeOfDay.now();
  }

  @override
  Widget build(BuildContext context) {
    return  Column(
      children: <Widget>[
         Text('日期选择'),
         RaisedButton(
          child:  Text('date selected:${_date.toString()}'),
          onPressed: () {
            _selectDate(context);
          },
        ),
         Text('时间选择'),
         RaisedButton(
          child:  Text('date selected:${_time.toString()}'),
          onPressed: () {
            _selectTime(context);
          },
        )
      ],
    );
  }
}