在颤动中改变Button的状态

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

我想在颤动中做的是当我按下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,),

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

dart flutter
2个回答
1
投票

这与单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,
            )
          ],
        ),
      ),
    );
  }
}

0
投票

你可以指定一个bool变量并在显示小部件的同时检查它,就像我在我的例子中所做的那样。或者你总是可以使用安全的setState,并始终确保你的小部件得到改变。这是一个简单的例子

bool enable = true;
Scaffold(
    body: Column(
  children: <Widget>[
    enable
        ? MaterialButton(
            child: Text("Button 1"),
            onPressed: () {
              enable = !enable;
            },
          )
        : Container(),
    !(enable)
        ? MaterialButton(
            child: Text("Button 2"),
            onPressed: () {
              enable = !enable;
            })
        : Container()
  ],
)),
© www.soinside.com 2019 - 2024. All rights reserved.