gpt4 book ai didi

flutter - 如何在timePicker中格式化时间

转载 作者:行者123 更新时间:2023-12-03 02:53:04 24 4
gpt4 key购买 nike

我正在尝试在我的 flutter 中实现一个时间选择器,它显示如下图所示的时间。

formated time

虽然我能够像这样格式化时间,但问题是它在小部件初始化时不显示当前时间。
我试过用这个。在这里看到我的代码。

TimeOfDay _currentTime = new TimeOfDay.now();

String timeText = 'Set A Time';
Future<Null> selectTime(BuildContext context) async {
TimeOfDay selectedTime = await showTimePicker(
context: context,
initialTime: _currentTime,
);

MaterialLocalizations localizations = MaterialLocalizations.of(context);
String formattedTime = localizations.formatTimeOfDay(selectedTime,
alwaysUse24HourFormat: false);

if (formattedTime != null) {
setState(() {
timeText = formattedTime;
});
}
};

Widget Date picker


class DatePicker extends StatelessWidget {
DatePicker({
this.formatedDate,
this.selectedDate,
});

final String formatedDate;
final Function selectedDate;

@override
Widget build(BuildContext context) {
return FlatButton(
padding: EdgeInsets.only(top: 30.0, bottom: 10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Icon(
Icons.calendar_today,
color: Color(kBorderTileColor),
),
SizedBox(
width: 50.0,
),
Text(
'$formatedDate',
style: kInputTextStyle,
),
SizedBox(
width: 50.0,
),
Text(
'All Day',
style: TextStyle(color: Color(kBorderTileColor)),
),
],
),
onPressed: () {
selectedDate(context);
},
);
}
}

最佳答案

试试这个源代码。

  TimeOfDay _currentTime = new TimeOfDay.now();
String timeText = 'Set A Time';


Future<Null> selectTime(BuildContext context) async {
TimeOfDay selectedTime = await showTimePicker(
context: context,
initialTime: _currentTime,
);

MaterialLocalizations localizations = MaterialLocalizations.of(context);
if (selectedTime != null) {
String formattedTime = localizations.formatTimeOfDay(selectedTime,
alwaysUse24HourFormat: false);
if (formattedTime != null) {
setState(() {
timeText = formattedTime;
});
}
}
}

void setCurrentTime(){
TimeOfDay selectedTime=new TimeOfDay.now();
MaterialLocalizations localizations = MaterialLocalizations.of(context);
String formattedTime = localizations.formatTimeOfDay(selectedTime,
alwaysUse24HourFormat: false);
if (formattedTime != null) {
setState(() {
timeText = formattedTime;
});
}
}

build(BuildContext context) 中调用此函数
 Widget build(BuildContext context) {
setCurrentTime();
...
}

关于flutter - 如何在timePicker中格式化时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com