tensixes
tensixes

Reputation: 131

How do you initialize a field in the State of a StatefulWidget in Flutter?

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

Upvotes: 12

Views: 18881

Answers (1)

Rebar
Rebar

Reputation: 1115

This is the perfect case for WidgetsBinding

just do this after super.initState();:

WidgetsBinding.instance.addPostFrameCallback((_) {
  setState(() {
    myBool = widget.initBool;
  });
});

this is where you're allowed to set States directly after init.

Upvotes: 3

Related Questions