我有一个应用程序,我想在每天使用 8 小时后禁用该按钮,以便能够在一天的 8 小时内随意使用它。
以下是部分按钮代码:
children: [
if (onMenuButtonPressed != null)
Align(
alignment: Alignment.centerLeft,
child: CupertinoButton(
onPressed: onMenuButtonPressed,
//onPressed: (DateTime.now().second >= 1 && DateTime.now().second <= 12) ? null : () => onMenuButtonPressed,
minSize: 0,
padding: const EdgeInsets.all(8),
child: const Icon(
Ionicons.menu,
color: ColorPalette.neutral50,
),
),
),
我尝试包含下面的代码,但它不起作用,并且被注释掉了:
onPressed: (DateTime.now().second >= 1 && DateTime.now().second <= 12) ? null : () => onMenuButtonPressed,
这样尝试你的代码,
DateTime? buttonPressedTime;
void handleMenuButtonPressed() {
if (buttonPressedTime == null || buttonPressedTime!.day != DateTime.now().day) {
buttonPressedTime = DateTime.now();
}
if (DateTime.now().difference(buttonPressedTime!) >= Duration(hours: 8)) {
// Disable the button
return;
}
}
// Usage of the button
children: [
if (onMenuButtonPressed != null)
Align(
alignment: Alignment.centerLeft,
child: CupertinoButton(
onPressed: handleMenuButtonPressed,
minSize: 0,
padding: const EdgeInsets.all(8),
child: const Icon(
Ionicons.menu,
color: ColorPalette.neutral50,
),
),
),
],