Open
Description
Use case
The StatefulBuilder
widget is useful for managing local state in a lightweight manner without requiring an entire StatefulWidget
. However, its current implementation lacks lifecycle methods such as initState
and dispose
, making it difficult to perform setup and cleanup actions within the widget.
To address this, i propose extending StatefulBuilder
to allow optional initState
and dispose
callbacks. This would enable developers to handle initialization and cleanup without needing to create a full StatefulWidget
.
Example:
StatefulBuilder(
initState: () => print("Initialized"),
dispose: () => print("Disposed"),
builder: (context, setState) {
return Column(
children: [
Text("Hello, World!"),
ElevatedButton(
onPressed: () => setState(() {}),
child: Text("Update"),
),
],
);
},
)
Proposal
API:
import 'package:flutter/material.dart';
class StatefulBuilder extends StatefulWidget {
const StatefulBuilder({
required this.builder,
this.initState,
this.dispose,
super.key,
});
final StatefulWidgetBuilder builder;
final void Function()? initState; // Maybe expose context ?
final void Function()? dispose;
@override
State<StatefulBuilder> createState() => _StatefulBuilderState();
}
class _StatefulBuilderState extends State<StatefulBuilder> {
@override
void initState() {
super.initState();
widget.initState?.call(); // Maybe expose context
}
@override
void dispose() {
widget.dispose?.call();
super.dispose();
}
@override
Widget build(BuildContext context) => widget.builder(context, setState);
}
Benefits:
- Allows lightweight stateful management with lifecycle methods.
- Eliminates the need for a full
StatefulWidget
in simple cases. - Reduces boilerplate while improving flexibility.
A small change, but it unlocks a lot of possibilities. I love to hear the Flutter team’s thoughts on this! 😃
👍 Yes, I like the proposal.
👎 No, I don't like the proposal.