Alex.F
Alex.F

Reputation: 6181

StatefulBuilder vs StatefulWidget

What is the difference between StatefulBuilder and StatefulWidget? When one should be used instead of the other?
At first glance they seem similar.
StatefulBuilder is defined:

A platonic widget that both has state and calls a closure to obtain its child widget

While StatefulBuilder is defined:

A widget that has mutable state

Upvotes: 16

Views: 20360

Answers (1)

Alex.F
Alex.F

Reputation: 6181

StatefulBuilder is actually a StatefulWidget under the hood.
So it's not that you would use one over the other. It's that StatefulBuilder is a specific implementation of StatefulWidget.

So we extend a StatefulWidget any time we want to create a custom Widget that has an inner state. And we use a StatefulBuilder in a very specific case when we want to expose the setState of the StatefulBuilder in a build method of another Widget. The updated Flutter documentation has a good video on StatefulBuilder.

In the example bellow we use StatefulBuilder to rebuild a Column containing 4 Radio widgets whenever the selected radio button changes:

await showDialog<void>(
  context: context,
  builder: (BuildContext context) {
    int? selectedRadio = 0;
    return AlertDialog(
      content: StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int? value) {
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

Upvotes: 18

Related Questions