flutter开发实战-ListWheelScrollView与自定义TimePicker时间选择器
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
TimeOfDay _time = TimeOfDay(hour: 8, minute: 0);
void _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _time,
);
if (picked != null && picked != _time) {
setState(() {
_time = picked;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListWheelScrollView(
itemCount: 1,
children: <Widget>[
OutlinedButton(
child: Text('Select Time'),
onPressed: () => _selectTime(context),
),
Text(
'Selected Time: ${_time.format(context)}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
}
extension TimeOfDayExtension on TimeOfDay {
String format(BuildContext context) {
return DateFormat.Hm(Localizations.localeOf(context).languageCode).format(toDateTime());
}
DateTime toDateTime() {
return DateTime.utc(2000, 1, 1, hour, minute);
}
}
这段代码定义了一个名为HomePage
的有状态小部件,它使用ListWheelScrollView
来展示一个OutlinedButton
,点击该按钮会调用_selectTime
方法,该方法会打开一个时间选择器(showTimePicker
),用户选择时间后更新状态。同时,它提供了一个TimeOfDayExtension
扩展,用于格式化时间并将TimeOfDay
转换为DateTime
对象。这个实例展示了如何在Flutter中创建一个自定义的时间选择器并处理用户的选择。
评论已关闭