【Flutter】表单 - Datapick,Timepick

2019-03-26  本文已影响0人  diva_dance

DatePick 和 Timepick 在 Flutter 里面没有对应的控件。只是提供两个函数:showDatePicker 和 showTimePicker

DatePick

打开日期选择器

RaisedButton(
    child: Text(_date != null ? _date : '点击'),
    onPressed: () {
        var picker = await showDatePicker(
          context: context,
          initialDate: new DateTime.now(),
          firstDate: new DateTime.now().subtract(new Duration(days: 30)), 
          lastDate: new DateTime.now().add(new Duration(days: 30)),      
        );
        setState(() {
          _date = picker.toString();
        });
    },
)

showDatePicker 接收参数有

ltr


image

rtl


image

1 设置国际化
在 pubspec.yaml 中设置

flutter_localizations:
    sdk: flutter

接着运行 flutter packages get 获取依赖库。

在对应 dart 文件中加入

import 'package:flutter_localizations/flutter_localizations.dart';

然后在 MaterialApp 的构造方法中赋值

localizationsDelegates: [                            
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [                                
    const Locale('zh','CH'),
    const Locale('en','US'),
],

再给 showDatePicker 的 local 设置成中文。

var picker = await showDatePicker(
  context: context,
  initialDate: new DateTime.now(),
  firstDate: new DateTime.now().subtract(new Duration(days: 30)),
  lastDate: new DateTime.now().add(new Duration(days: 30)),
  locale: Locale('zh')
);
setState(() {
  _date = picker.toString();
});
image

关于国际化参考: https://www.jianshu.com/p/8356a3bc8f6c

Timepick

设置时间选择器

void _showTimePick() async {
    var picker = await showTimePicker(
        context: context,
        initialTime: new TimeOfDay(hour: 2, minute: 2)
    );
    setState(() {
        _date = picker.toString();
    });
}
image

参数

上一篇下一篇

猜你喜欢

热点阅读