Skip to content

Expand StatefulBuilder to Support initState and dispose #164112

Open
@stan-at-work

Description

@stan-at-work

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: new featureNothing broken; request for a new capabilityc: proposalA detailed proposal for a change to Flutterframeworkflutter/packages/flutter repository. See also f: labels.team-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions