需求是要实现一个IOS风格的时间日期选择器。
需要注意的点:如果你的项目里做了国际化--例如中文,那么在构建这个组件时会报错。需要自己做本地化配置。
void _showCupertinoDatePicker() {
showModalBottomSheet(
context: context,
builder: (context) {
return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
'取消',
style: TextStyle(fontSize: 13),
)),
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
'确认',
style: TextStyle(fontSize: 13),
)),
],
),
Container(
height: MediaQuery.of(context).copyWith().size.height / 3,
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,//这里改模式
maximumYear: initialDate.year,
minimumYear: initialDate.year - 60,
onDateTimeChanged: (dateTime) {
print( "${dateTime.year}-${dateTime.month}-${dateTime.day}")
}),
),
]);
});
}
这时候时间选择器是英文的,那么想要一个中文的时间选择器。需要添加本地化
supportedLocales: [
const Locale('en', 'US'), // 美国英语
const Locale('zh', 'CN'), // 中文简体
//其它Locales
],
而使用了中文之后。。就会报错
解决构建时报错的方法:
import 'package:flutter_localizations/flutter_localizations.dart';
new MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,//多加这行代码
],
supportedLocales: [
const Locale('en', 'US'), // 美国英语
const Locale('zh', 'CN'), // 中文简体
//其它Locales
],
// ...
)
至于这个国际化,引入这个包就行。具体请参考这里
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter