Back to results for “Set”
Flutter › State Management with setState

How can you properly lift shared state up to a genuinely common ancestor StatefulWidget when two separate sibling widgets genuinely both need to access and properly react to that exact same particular piece of shared data?

Advanced

Answer

Lifting state up means properly moving a given piece of shared state from wherever it might have originally been more narrowly located up to the genuinely nearest common ancestor widget that both of the separate sibling widgets requiring that same particular data actually genuinely share, then properly passing that data back down to each individual sibling as a regular constructor parameter, along with a genuine callback function that lets a given sibling properly notify that shared ancestor whenever it genuinely needs to actually update that particular shared value, and while this particular pattern genuinely works reasonably well for a fairly shallow, quite simple widget tree, it can genuinely become considerably more unwieldy and awkward as your particular tree grows deeper, which is precisely the exact specific kind of scenario a genuinely more dedicated external state management solution like Provider is specifically designed to properly solve.
class ParentWidget extends StatefulWidget {
  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  int _sharedValue = 0;
  // Passed down to both sibling children, along with an update callback
}
Real-world example A form screen properly lifts its own shared validation error state up to a genuinely common parent StatefulWidget so both a separate input field and a separate error message display widget can each properly access that exact same shared error state without needing any dedicated external state management package at all.

Common follow-ups: At what specific point does lifting state up become considerably more genuinely cumbersome than simply adopting Provider instead?;How does this exact same lifting state up pattern genuinely relate more broadly to React's own considerably similar well known state management philosophy?