StatefulBuilderはビルダーのsetStateを実行するとビルダークロージャで作成しているWidgetが再構築されるWidgetである。
ビルダークロージャ外に存在する変数をsetStateで更新して再構築に反映させることができる。
状態を利用できるようにするWidgetといえる。
StatefulBuilderのドキュメントに「platonic widget」とある。The use of term "platonic" is confusing · Issue #48137 · flutter/flutterなどからすると、simpleと受け取っておくと良さそう。
StatefulBuilderは外部の状態を更新するのでコードの複雑性が増すという欠点がある。
よって、ユースケースとしてはStatelessWidgetの一部で状態を使いたい場合に利用するなど、小さく利用すると良い。例えば以下のようにStatelessWidgetで表示したアラートで状態が必要な場合に役に立つ。
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
bool isChecked = false;
return StatefulBuilder(builder: (context, setState) {
return AlertDialog(
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Confirm"),
Checkbox(
value: isChecked,
onChanged: (checked) => setState(() => isChecked = checked ?? false),
)
],
),
title: const Text('Stateful Dialog'),
actions: <Widget>[
OutlinedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: isChecked ? () => Navigator.of(context).pop() : null,
child: const Text('OK'),
),
],
);
});
});
},
child: const Text('Show alert'),
);
}
}
チェックボックスをオンにするとisCheckedがtrueになり、OKをタップできるようになる。