白天使用数小时后禁用按钮

问题描述 投票:0回答:1

我有一个应用程序,我想在每天使用 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,
flutter dart button
1个回答
0
投票

这样尝试你的代码,

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,
        ),
      ),
    ),
],
© www.soinside.com 2019 - 2024. All rights reserved.