Flutter开发之——日期选择器
import 'package:flutter/material.dart';
class DatePickerPage extends StatefulWidget {
@override
_DatePickerPageState createState() => _DatePickerPageState();
}
class _DatePickerPageState extends State<DatePickerPage> {
DateTime _selectedDate = DateTime.now();
void _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(2020),
lastDate: DateTime(2025),
);
if (picked != null && picked != _selectedDate) {
setState(() {
_selectedDate = picked;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Date Picker Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('${_selectedDate.toLocal()}'),
RaisedButton(
child: Text('Select Date'),
onPressed: () => _selectDate(context),
),
],
),
),
);
}
}
这段代码实现了一个简单的日期选择器,用户可以通过点击按钮打开日期选择器,选择日期后更新界面上显示的日期信息。这个例子展示了如何在Flutter应用中使用showDatePicker
函数来实现日期选择的功能。
评论已关闭