Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing state of Button in flutter

Tags:

flutter

dart

What i want to do in flutter is when i press button1 it enables button2 and then it disables himself and i want to do the same for 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,),

But it's not working for me, because when i press button1 nothing happens.

like image 595
yashthakkar1173 Avatar asked Sep 14 '25 20:09

yashthakkar1173


1 Answers

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,
            )
          ],
        ),
      ),
    );
  }
}
like image 135
anmol.majhail Avatar answered Sep 16 '25 13:09

anmol.majhail