首页 > 解决方案 > 在颤动中改变按钮的状态

问题描述

我想要在颤动中做的是当我按下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 时没有任何反应。

标签: dartflutter

解决方案


This Works with Single bool Variable :

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

Also In your Code SetState is not Correct:

it Should Be:

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

推荐阅读