Flutter学习笔记

Flutter 的时间和日期选择器

2019-10-10  本文已影响0人  王俏

showDatePicker 和 showTimePicker

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';

class DateTimeDemo extends StatefulWidget {
  @override
  _DateTimeDemoState createState() => _DateTimeDemoState();
}

class _DateTimeDemoState extends State<DateTimeDemo> {
  DateTime selectedDate = DateTime.now();

  TimeOfDay selectedTime = TimeOfDay(hour: 9, minute: 30);

  Future<void> _selectDate() async //异步
  {
    final DateTime date = await showDatePicker( //等待异步处理的结果
      //等待返回
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
    );
    if (date == null) return; //点击DatePicker的cancel

    setState(() {
      //点击DatePicker的OK
      selectedDate = date;
    });
  }

  Future<void> _seletedTime() async {//异步
    final TimeOfDay time = await showTimePicker( //等待异步处理的结果
      context: context,
      initialTime: selectedTime,
    );
    if (time == null) return;

    setState(() {
      selectedTime = time;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DateTimeDemo'),
        elevation: 0.0,
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                InkWell(
                  //包装一个相应点击的组件
                  onTap: _selectDate,
                  child: Row(
                    children: <Widget>[
                      // Text(DateFormat.yMd().format(selectedDate)),// 5/10/2019
                      // Text(DateFormat.yMMM().format(selectedDate)),// May 2019
                      Text(DateFormat.yMMMd()
                          .format(selectedDate)), // May 10, 2019
                      // Text(DateFormat.yMMMMd().format(selectedDate)),// May 10, 2019
                      Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
                InkWell(
                  //包装一个相应点击的组件
                  onTap: _seletedTime,
                  child: Row(
                    children: <Widget>[
                      Text(selectedTime.format(context)), // May 10, 2019
                      Icon(Icons.arrow_drop_down),
                    ],
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}


DatePicker.png TimePicker.png
上一篇下一篇

猜你喜欢

热点阅读