dart - 在 flutter 中改变按钮的状态

标签 dart flutter

我想在 flutter 中做的是当我按下 button1 它启用 button2 然后它禁用自己,我想对 button2 做同样的事情。

bool button1 = true;
bool button2 = false;

void _button1(){
    setState(){
      button1=false;button2=true;
    }
  }
void _button2(){
    setState(){
      button1=true;button2=false;
    }
  }

new MaterialButton(onPressed: button1 ? _button1 :null,child: Text("button1"),color: Colors.greenAccent,),
new MaterialButton(onPressed: button2 ? _button2 :null,child: Text("button2"),color: Colors.greenAccent,),

但这对我不起作用,因为当我按下 button1 时没有任何反应。

最佳答案

这适用于单个 bool 变量:

class Page1State extends State<Page1> {
  bool buttonState = true;

  void _buttonChange() {
    setState(() {
      buttonState = !buttonState;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Button State'),
        ),
        body: Center(
            child: Wrap(
          children: <Widget>[
            MaterialButton(
              onPressed: buttonState ? _buttonChange : null,
              child: Text("button1"),
              color: Colors.greenAccent,
            ),
            MaterialButton(
              onPressed: buttonState ? null : _buttonChange,
              child: Text("button2"),
              color: Colors.greenAccent,
            ),
          ],
        )));
  }
}

另外在您的代码中 SetState 不正确:

应该是:

  bool button1 = true;
  bool button2 = false;

  void _button1() {
    setState(() {
      button1 = false;
      button2 = true;
    });
  }

  void _button2() {
    setState(() {
      button1 = true;
      button2 = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Button State"),
      ),
      body: Center(
        child: Wrap(
          children: <Widget>[
            MaterialButton(
              onPressed: button1 ? _button1 : null,
              child: Text("button1"),
              color: Colors.greenAccent,
            ),
            MaterialButton(
              onPressed: button2 ? _button2 : null,
              child: Text("button2"),
              color: Colors.greenAccent,
            )
          ],
        ),
      ),
    );
  }
}

关于dart - 在 flutter 中改变按钮的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52342515/

相关文章:

dart - 使用 MaterialApp 路由在屏幕旋转时调用 Widget 的 didUpdateWidget 方法

dart - 使用 flutter 的集合中的值(value)总和

android - Flutter 应用程序中 firebase 数据库上的 ValueEventListener

Flutter 应用程序错误 - 类型 'Timestamp' 不是类型 'DateTime' 的子类型

dart - Flutter - 创建不同类型的列表 - 示例 (i) => i % 6 == 0 ?

dart - WebStorm和Dart自动完成

flutter - Flutter 中基于百分比的布局

dart - 安装后,Flutter 发布的应用程序无法在设备上运行

flutter - 我应该总是在我的 flutter 屏幕的顶层使用 SafeArea 吗?

android - flutter ,云火存储查询方法,其中无法正常工作