Flutter 中的 CupertinoTimePicker 小部件:全面指南
在Flutter中,CupertinoTimePicker是一个用于选择时间的小部件,它专为iOS风格应用设计。以下是如何使用CupertinoTimePicker的示例代码:
import 'package:flutter/cupertino.dart';
class TimePickerExample extends StatefulWidget {
@override
_TimePickerExampleState createState() => _TimePickerExampleState();
}
class _TimePickerExampleState extends State<TimePickerExample> {
TimeOfDay _selectedTime = TimeOfDay.now();
void _selectTime(BuildContext context) async {
final TimeOfDay? picked = await showCupertinoModalPopup<TimeOfDay>(
context: context,
builder: (BuildContext context) {
return CupertinoTimePicker(
initialTime: _selectedTime,
onChanged: (TimeOfDay newTime) {
setState(() {
_selectedTime = newTime;
});
},
);
},
);
if (picked != null && picked != _selectedTime) {
setState(() {
_selectedTime = picked;
});
}
}
@override
Widget build(BuildContext context) {
return CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
trailing: CupertinoButton(
child: Text('选择时间'),
onPressed: () => _selectTime(context),
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('选择的时间: $_selectedTime'),
],
),
),
),
);
}
}
这段代码创建了一个CupertinoTimePicker,并通过showCupertinoModalPopup在弹出窗口中显示。用户可以通过滑动选择时间,选择的时间将通过回调函数更新到_selectedTime
变量中。这个例子展示了如何在Flutter应用中整合CupertinoTimePicker,并且如何处理用户的选择。
评论已关闭