Flutter日期选择插件date_only的使用
Flutter日期选择插件date_only的使用
本README描述了该包。如果你将此包发布到pub.dev,此README的内容会出现在你的包的首页。
特性
DateOnly dateOnly = DateOnly.today();
print('年: ${dateOnly.year}');
print('月: ${dateOnly.month}');
print('日: ${dateOnly.day}');
开始使用
dart pub add date_only
使用方法
import 'package:date_only/date_only.dart';
final DateOnly dateOnlyForToday = DateOnly.today();
final DateOnly dateOnlyFromDateTime = DateOnly.fromDateTime(DateTime(2023, 10, 1));
示例代码
以下是一个完整的示例,展示了如何在Flutter应用中使用date_only
插件:
import 'package:flutter/material.dart';
import 'package:date_only/date_only.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("日期选择插件使用示例"),
),
body: Center(
child: DatePickerDemo(),
),
),
);
}
}
class DatePickerDemo extends StatefulWidget {
[@override](/user/override)
_DatePickerDemoState createState() => _DatePickerDemoState();
}
class _DatePickerDemoState extends State<DatePickerDemo> {
DateOnly _selectedDate;
void _showDatePicker() async {
final pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2000),
lastDate: DateTime(2100),
);
if (pickedDate != null) {
setState(() {
_selectedDate = DateOnly.fromDateTime(pickedDate);
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _showDatePicker,
child: Text("选择日期"),
),
SizedBox(height: 20),
if (_selectedDate != null)
Text(
"选择的日期: ${_selectedDate.year}-${_selectedDate.month}-${_selectedDate.day}",
style: TextStyle(fontSize: 18),
)
],
);
}
}
更多关于Flutter日期选择插件date_only的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复