如果单击另一个按钮,如何禁用按钮?

时间:2021-06-29 20:42:01

标签: flutter

我刚刚开始掌握 Flutter 的窍门,但我无法弄清楚如何在单击另一个按钮时禁用按钮

目前我有 20 个按钮,每个按钮都可以选择让我们说

enter image description here

目前我有 20 个布尔值检查每个按钮是否被选中(我已经知道它可以更容易地完成,但没有想到)

如何选择一个按钮,然后如果单击另一个按钮,AlertDialog 会显示两个选项(取消或继续)?

如果您选择取消,一切都会保持原样,但如果您选择继续,您单击的按钮现在处于活动状态,而您之前单击的按钮变为非活动状态

这是当您单击按钮编号 1 时发生的情况

enter image description here

1 个答案:

答案 0 :(得分:0)

也许更改布尔值列表的所有布尔值会更容易执行您需要的操作。 每个按钮都有一个用于标识自身的索引,他的索引将是您将创建的列表中的索引。

final buttonsState = List.generate(20, (index) => false, growable: false);

上面的列表将是您的按钮状态。对国家来说就是这样。

关于主要问题... 首先你需要让你的按钮成为一个组件,让你可以重用它,就像这样:

class ButtonWidget extends StatefulWidget {
  /// Identifier for your button
  final int index;

  /// The whole list of your buttons state
  final List<bool> currentStates;

  const ButtonWidget({required this.index, required this.currentStates});

  @override
  _ButtonWidgetState createState() => _ButtonWidgetState();
}

class _ButtonWidgetState extends State<ButtonWidget> {
  /// If the button was selected will be enabled
  bool get selected => widget.currentStates[widget.index];

  void showDialogConfirm(BuildContext context) {
    showDialog(
      context: context,
      builder: (_) {
        return AlertDialog(
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  /// clearing the list
                  widget.currentStates.clear();

                  /// setting the whole list to false
                  widget.currentStates
                      .addAll(widget.currentStates.map((e) => false));

                  /// setting the index of your button to true
                  widget.currentStates[widget.index] = true;

                  /// and pop
                  Navigator.of(context).pop();
                });
              },
              child: const Text('Continue'),
            )
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () => showDialogConfirm(context),
      child: Text('Button: ${widget.index} is $selected'),
    );
  }
}

你可以像这样使用按钮:

class UsingTheButtonWidget extends StatelessWidget {
  final buttonsState = List.generate(20, (index) => false, growable: false);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ButtonWidget(index: 1, currentStates: buttonsState),
        ButtonWidget(index: 2, currentStates: buttonsState),
        ButtonWidget(index: 3, currentStates: buttonsState),
        ButtonWidget(index: 4, currentStates: buttonsState),
        ButtonWidget(index: 5, currentStates: buttonsState),
        ButtonWidget(index: 6, currentStates: buttonsState),
      ],
    );
  }
}

因此,每次单击按钮时,都会打开对话框。 当您单击继续时,您将取消选择所有其他按钮并选择您单击的一个。 附:在这个例子中,我只使用了 flutter,没有任何库。

相关问题