flutter写一个时间选择器
时间: 2024-04-25 22:06:42 浏览: 109
flutter日期选择器 flutter时间选择器
以下是Flutter中的时间选择器示例代码:
```dart
import 'package:flutter/material.dart';
class TimePickerDemo extends StatefulWidget {
@override
_TimePickerDemoState createState() => _TimePickerDemoState();
}
class _TimePickerDemoState extends State<TimePickerDemo> {
TimeOfDay _time = TimeOfDay.now();
Future<void> _selectTime(BuildContext context) async {
final TimeOfDay? newTime =
await showTimePicker(context: context, initialTime: _time);
if (newTime != null) {
setState(() {
_time = newTime;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Time Picker Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Selected Time:',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 10),
Text(
_time.format(context),
style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () => _selectTime(context),
child: Text('Select Time'),
),
],
),
),
);
}
}
```
上述代码中的`_selectTime()`方法使用`showTimePicker`函数来显示时间选择器,并根据用户选择更新当前选定的时间。`_time.format(context)`方法将选定的时间格式化为可读的文本并显示在屏幕上。在此示例中,我们使用了`ElevatedButton`来显示一个按钮,以便用户可以打开时间选择器并选择时间。
阅读全文