Reputation: 1391
I am using this package which toggles a boolean variable value. I am using this boolean variable to show/hide a text widget. Although the value changes,the widget isn't affected at all. What am I missing here?
SwitcherButton(
key: UniqueKey(),
value: showDiscount,
onColor: Colors.greenAccent,
offColor: Colors.grey,
onChange: (value) {
showDiscount = !value;
}),
if(showDiscount) Text('Hello')
Upvotes: 3
Views: 2280
Reputation: 63604
you are making showDiscount = !value;
make use using statefullWidget
.
but your mistake is not using setState()
replace
onChange: (value) {
showDiscount = !value;
}),
with
onChange: (value) {
setState((){ showDiscount = !value;})
}),
I suggest using the Visibility
widget. it controls visibility of any Widget. it doesn't take size while it is not visible.
here is the demo:
import 'package:flutter/material.dart';
import 'package:switcher_button/switcher_button.dart';
class HideAndSeek extends StatefulWidget {
HideAndSeek({Key? key}) : super(key: key);
@override
_HideAndSeekState createState() => _HideAndSeekState();
}
class _HideAndSeekState extends State<HideAndSeek> {
bool _isVisible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Text("Hey Check It "),
SwitcherButton(
value: true,
onChange: (value) {
setState(() {
_isVisible = value;
});
},
),
Visibility(
visible: _isVisible,
child: new Text('Boom'),
),
if (_isVisible) Text("Hoiaaaaaaa"),
Icon(Icons.upcoming),
],
),
),
);
}
}
Upvotes: 4
Reputation: 3062
You need to set state and change the test as bellow.
SwitcherButton(
key: UniqueKey(),
value: showDiscount,
onColor: Colors.greenAccent,
offColor: Colors.grey,
onChange: (value) {
setState(){
showDiscount = !value;
}
}),
showDiscount ? Text('Hello') : Container(),
Upvotes: 0
Reputation: 2060
Use Stateful Widget if you are using Stateless Widget and add setState method inside onChange
onChange: (value) {
setState(() {
showDiscount = !value;
});
}),
Upvotes: 0