Reputation: 359
I am trying to change some bool values in my Dialog. I am doing like this
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
bool testBool = true;
return Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(12.0),
side: BorderSide(
color:
kPrimaryColor)), //this right here
child: GestureDetector(
onTap: (){
print(testBool);
setState((){
testBool = !testBool;
});
print(testBool);
},
child: Container(
height: 525,
width: width * 0.85,
child:
Text('12313', style: TextStyle(color: testBool? Colors.red : Colors.green),),
),
),
);
},
);
},
);
But its not changing the color, I mean to say its not changing testBool
state in Dialog.
Upvotes: 3
Views: 5866
Reputation: 1709
As CopsOnRoad mentioned the bool testBool = true;
is in the wrong place. When you call setState, it rebuilds the widget and when it rebuilds the widget it defines testBool and sets it to true. The variable testBool should be a field in the state class the dialog is being built in.
Upvotes: 1
Reputation: 1814
You have to define the variable testbool
outside the StatefulBuilder
, because whenever you perform setState
, the program under StatefulBuilder
rebuilds and so the variavle testbool
is defined again.
Upvotes: 1
Reputation: 267454
Your code is fine but you're putting the bool
condition within the builder
which is why every time you call setState
it is again set to true
.
showDialog(
context: context,
builder: (context) {
bool testBool = true; // This flag should be here.
return StatefulBuilder(
builder: (context, setState) {
// ...
},
);
},
);
Upvotes: 5