I have something like this where a widget's color depends on a bool, and the bool flips when you tap on the widget. But I also want to initialize the bool, which will be different for different instances of the widget. I tried something like this where the StatefulWidget class contains the initial value initBool, which is used in initState to set myBool.
It seems to work (but honestly I'm not sure because I'm getting a strange bug but I can't figure out if it's related or not), but it just feels a little clunky, so I was wondering if there's a more appropriate way to do this in Flutter. Thanks!
class MyBox extends StatefulWidget {
final bool initBool;
MyBox(this.initBool);
@override
_MyBoxState createState() => _MyBoxState();
}
class _MyBoxState extends State<MyBox> {
bool myBool;
@override
void initState() {
super.initState();
myBool = widget.initBool;
}
@override
Widget build(BuildContext context) {
return InkWell(
child: Container(
color: myBool ? Colors.green : Colors.red
),
onTap: () {
setState(() {
myBool = !myBool;
});
},
);
}
}