<FlutterSolution/> flutter · dart · clean architecture

Flutter Prep #18 StatelessWidget vs StatefulWidget




You already know the lifecycle. This post covers what lifecycle diagrams skip: why Flutter has two widget types, what extends is really buying you, what setState does line by line, and exactly why one setState does not rebuild the parent, the siblings, or most nested children. Plain definitions first, then source-level detail. Written against Flutter 3.50 (November 2026) and Dart 3.14. About 20 minutes.

Flutter 3.50Dart 3.14WidgetssetStateRebuild scopeInterview ready

The short answer

StatelessWidget

Output depends only on its inputs

A widget whose UI is fully decided by its constructor arguments and inherited data (Theme, MediaQuery). It remembers nothing between builds.

Think of it as a printed poster: same text in, same poster out.

StatefulWidget

Widget + a separate State object

A widget paired with a long-lived State object that keeps data between rebuilds and can ask for a rebuild with setState.

Think of it as a whiteboard: you can erase and rewrite it while it hangs on the wall.

setState in one sentence setState runs your callback immediately, marks one Element as dirty, and at the next frame Flutter re-runs that element's build and compares the result with what is already on screen. Nothing else is touched unless that comparison says it must be.

First principles: Widget, Element, RenderObject

Everything else in this post depends on three objects that Flutter keeps in three parallel trees.

Widget

An immutable description

A small, cheap object that says “put a Text with this string here”. Flutter throws widgets away and creates new ones on every build.

The blueprint page.

Element

The live object at one spot

Created when a widget is first mounted and then reused. It holds the current widget, its parent and children, and, for stateful widgets, the State.

The site manager who stays at the plot and receives new blueprints.

RenderObject

Does layout and painting

Measures, positions and paints. More expensive, so it is also kept alive and only updated when a property really changed.

The actual building.

Widget treeimmutable, recreated every build
→
Element treepersistent, decides what to reuse
→
RenderObject treelayout + paint, updated only if needed
→
Pixelson screen
Why this matters Widgets are disposable, so anything that must survive a rebuild cannot live in a widget field. That one fact is the whole reason StatefulWidget has a second class.

Two framework details worth knowing now. First, Widget is marked @immutable, so every field must be final and the analyzer warns you otherwise. Second, Widget.operator == is marked @nonVirtual: you cannot override it. Flutter never compares widget fields, it only asks “is this the exact same instance?”. Keep that in mind, it explains the rebuild rules later.

StatelessWidget, from A to Z

Definition A StatelessWidget is a widget whose build method is a pure description of the UI for the given constructor arguments and the inherited data it reads from BuildContext.
Dart · stateless
import 'package:flutter/widgets.dart';

class GreetingCard extends StatelessWidget {
  const GreetingCard({super.key, required this.name, this.onTap});

  final String name;               // config: always final
  final VoidCallback? onTap;       // callbacks are config too

  @override
  Widget build(BuildContext context) {
    final scale = MediaQuery.textScalerOf(context);   // inherited data is allowed
    return GestureDetector(
      onTap: onTap,
      child: Text('Hello, $name', textScaler: scale),
    );
  }
}

What each part is for

PieceWhat it doesWhy it exists
extends StatelessWidgetInherits createElement(), key handling and diagnostics.You only fill in the one blank the framework cannot guess: build.
const constructorLets callers write const GreetingCard(...).A const instance is created once and reused, so Flutter can skip it on rebuilds.
super.keyPasses the optional key to Widget.Keys control Element reuse (see the rebuild section).
final fieldsHold the configuration.The class is @immutable. A mutable field would be lost on the next rebuild anyway.
build(BuildContext)Returns the child widget(s).context is this widget's Element. Use it to look up inherited data.

What you can and cannot do

You canYou cannot
Compose other widgets, use local variables, loops and conditions inside build.Remember a value between builds (a counter, a toggle).
Read inherited data: Theme.of(context), MediaQuery.of(context), Navigator.of(context).Own an AnimationController, TextEditingController, FocusNode or timer (nothing disposes them).
Call callbacks given by the parent, so the parent can change state.Ask to be rebuilt by itself. It has no setState.

When does a StatelessWidget rebuild?

Only four things cause it, and none of them come from inside the widget:

1. Its parent rebuilt and created a new instance of it. 2. An InheritedWidget it depends on changed (Theme, MediaQuery, Provider). 3. It is mounted for the first time. 4. Hot reload.

Myth: stateless means static A stateless widget can show different UI every second if its parent keeps passing new values. “Stateless” only means this widget owns no data. Also, if the parent passes a new instance with identical field values, Flutter still rebuilds it, because it compares instances, not fields.

StatefulWidget, from A to Z

Definition A StatefulWidget is an immutable widget that creates a separate, mutable State object. The widget is the configuration and is recreated often. The State is the memory and lives as long as its Element stays in the tree.
Dart · stateful
class Counter extends StatefulWidget {
  const Counter({super.key, required this.step});
  final int step;                                   // config from the parent

  @override
  State<Counter> createState() => _CounterState();  // called once per mounted Element
}

class _CounterState extends State<Counter> {
  int _count = 0;                                   // memory: survives rebuilds

  void _increment() {
    setState(() {
      _count += widget.step;                        // widget = newest config
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _increment,
      child: Text('Count: $_count'),
    );
  }
}

Why two classes?

Because the two halves live for different lengths of time. If the counter lived in the widget, the parent's next rebuild would create a fresh widget and the count would reset to zero. Moving the data into a separate object that the Element holds keeps it alive.

ObjectLives forHolds
Counter (widget)One build. Replaced on every parent rebuild.Configuration such as step.
_CounterStateFrom mount until the Element leaves the tree.Mutable data, controllers, subscriptions.
StatefulElementWhile the same type and key sit at that spot.Current widget + the State.

The parts of a State, explained

PieceMeaning
State<Counter>The generic bound T extends StatefulWidget gives you a correctly typed widget getter. Without it, widget.step would not compile.
widgetAlways the newest configuration. When the parent rebuilds, Flutter swaps it in and calls didUpdateWidget.
contextThe Element of this State. It is the same object for the State's whole life.
mountedtrue while the State is attached to the tree. It becomes false after dispose.
_CounterState (underscore)A private class: nobody outside the file should touch your State. Only createState returns it.
createState()Called once when the Element is created. Inserting the same widget instance in two places creates two separate States.

Lifecycle hooks, only as they relate to setState

You know the order already. Here is what each hook means for rebuilding:

HooksetState needed?Note
initStateNoSet fields directly. The first build follows anyway.
didChangeDependenciesNoA build follows. Use it when an InheritedWidget you read changes.
didUpdateWidget(old)NoCompare old with widget, update fields. A build follows automatically.
buildNever call it hereCalling setState inside build throws an error.
disposeNever call it hereRelease controllers. After this, mounted is false.

extends, implements, with, on: what the keywords buy you

These Dart keywords show up in every widget file. Here is what each one means in Flutter terms.

KeywordMeaningFlutter exampleWhy this choice
extendsInherit the full implementation. One parent only.class A extends StatelessWidgetYou get createElement, keys and diagnostics for free and only write build.
implementsPromise to provide every member yourself. No code is inherited.implements PreferredSizeWidgetGood for adding a capability (an interface). Using it instead of extends on a widget would force you to rewrite the whole Widget class.
withMix in reusable code from a mixin. Many allowed.with SingleTickerProviderStateMixinShares behavior across unrelated classes without a deep hierarchy.
on (in a mixin)Restricts which classes may use the mixin.mixin Foo on State<T>The mixin can safely call setState or read widget.
abstractCannot be instantiated. Subclasses must fill the blanks.StatelessWidget, StatefulWidgetForces you to implement build or createState.

Putting all of them in one real widget: a custom header that extends a widget, implements an interface, and a State that mixes in a ticker.

Dart · extends, implements, with
// extends + implements together
class FsHeader extends StatelessWidget implements PreferredSizeWidget {
  const FsHeader({super.key});

  @override
  Size get preferredSize => const Size.fromHeight(56);   // required by the interface

  @override
  Widget build(BuildContext context) =>
      const ColoredBox(color: Color(0xFF02569B), child: SizedBox(height: 56));
}

// extends + with (mixin)
class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
  late final AnimationController _c = AnimationController(
    vsync: this,                                        // 'this' is a TickerProvider thanks to the mixin
    duration: const Duration(seconds: 1),
  )..repeat(reverse: true);

  @override
  void dispose() {
    _c.dispose();                                       // State owns it, State must free it
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => FadeTransition(
        opacity: _c,
        child: const SizedBox(width: 64, height: 64, child: ColoredBox(color: Color(0xFF02569B))),
      );
}

The widget family tree

ClassExtendsElement it createsUsed for
StatelessWidgetWidgetStatelessElementCompose other widgets, no memory.
StatefulWidgetWidgetStatefulElementCompose + memory + setState.
InheritedWidgetProxyWidgetInheritedElementShare data down the tree (Theme, MediaQuery, Provider).
RenderObjectWidgetWidgetRenderObjectElementLeaf and layout widgets that really paint (Padding, Text, Flex).

Notice the pattern: Widget is only the description, and each subclass decides which kind of Element will manage it. State is not a widget at all. It is a separate class that mixes in Diagnosticable and is held by a StatefulElement.

What setState really does

Here is the whole mechanism, simplified from the framework source:

Dart · simplified source
// simplified from flutter/lib/src/widgets/framework.dart
void setState(VoidCallback fn) {
  assert(mounted);                    // debug only: not after dispose()
  final Object? result = fn();        // 1. your callback runs NOW, synchronously
  assert(result is! Future);          // debug only: async callbacks are rejected
  _element!.markNeedsBuild();         // 2. flag this ONE element as dirty
}

void markNeedsBuild() {
  if (!_active) return;
  if (dirty) return;                  // already queued: extra setState calls are batched
  _dirty = true;
  owner!.scheduleBuildFor(this);      // 3. add to the dirty list and request a frame
}

Notice what is not there: no rebuild happens inside setState. It only changes data and raises a flag. The rebuild happens later, at the next frame.

setState()runs your callback
→
markNeedsBuildthis Element becomes dirty
→
scheduleBuildForadded to the dirty list, frame requested
→
next framevsync, roughly every 16 ms at 60 Hz
→
buildScopedirty elements rebuilt, parents first
→
updateChildold vs new widget diff
→
layout + paintonly where something changed

Step by step at the frame

1. The engine signals a frame. 2. The BuildOwner sorts the dirty elements by depth, so parents rebuild before children. If a parent's rebuild already refreshed a dirty child, the child's flag is cleared and it is not built twice. 3. For each dirty element, Flutter calls state.build(), which returns a new widget subtree. 4. The Element compares it with its old child (updateChild, next section). 5. For widgets that own a RenderObject, updateRenderObject assigns the new properties. Each setter calls markNeedsLayout or markNeedsPaint only if the value actually changed. 6. Layout, paint and compositing run, and pixels reach the screen.

setState rules

RuleWhat happens if you break it
The callback is synchronous.An async callback fails an assertion in debug: the framework cannot wait for a Future.
Change the data inside the callback (or just before it).Both work, because the build runs later. Inside the callback is the convention and keeps intent clear.
Change data without calling setState.The field changes, but no build is scheduled, so the screen stays stale until something else rebuilds it.
Never call it during build.Error: setState() or markNeedsBuild() called during build.
Never call it after dispose.Error: setState() called after dispose(). Check mounted after every await.
Many calls in one frame are fine.They share a single dirty flag, so you still get one build.
Dart · right and wrong
// ❌ stale UI: data changed, nobody asked for a rebuild
void bad() => _count++;

// ❌ assertion: callback returns a Future
void bad2() => setState(() async {
      _user = await repo.load();
    });

// ✅ do async work first, then one small synchronous setState
Future<void> load() async {
  final user = await repo.load();
  if (!mounted) return;                      // the screen may be gone after the await
  setState(() => _user = user);
}

Why only one nested stateful widget rebuilds

This is the question behind the whole post. There are three facts, and together they explain every case.

Fact 1

The dirty flag is per Element

setState marks the Element of the State that called it. Not the parent, not the siblings, not the root.

One sticky note on one door.

Fact 2

The rebuild walks downward only

The dirty element runs build and then diffs its children, then their children, and so on. It never goes up.

Water flows down the tree.

Fact 3

The walk stops at an identical instance

If the new child widget is the same instance as the old one, Flutter skips it. That is what const and cached widgets give you.

A “nothing changed here” sign.

Here is the diff step, simplified. This tiny method is the heart of Flutter's rebuild optimisation:

Dart · simplified source
// simplified Element.updateChild
Element? updateChild(Element? child, Widget? newWidget, Object? newSlot) {
  if (newWidget == null) {
    if (child != null) deactivateChild(child);
    return null;
  }
  if (child != null) {
    if (child.widget == newWidget) {         // same instance (const / cached)
      if (child.slot != newSlot) updateSlotForChild(child, newSlot);
      return child;                             // ⛔ SKIP: no build, no descendants visited
    }
    if (Widget.canUpdate(child.widget, newWidget)) {   // same runtimeType AND same key
      child.update(newWidget);                  // reuse Element (and its State!), then rebuild it
      return child;
    }
    deactivateChild(child);                     // different type or key: throw it away
  }
  return inflateWidget(newWidget, newSlot);     // brand-new Element (and a brand-new State)
}

A demo you can run

One parent screen and three children: a const stateful counter (A), a non-const stateful counter (B), and a stateless badge. Every build prints a log line.

Dart · rebuild demo
// If you have not migrated yet (Flutter 3.46 or older), replace the first two imports
// with: import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:material_ui/material_ui.dart';

void main() => runApp(const MaterialApp(home: ParentScreen()));

class ParentScreen extends StatefulWidget {
  const ParentScreen({super.key});
  @override
  State<ParentScreen> createState() => _ParentScreenState();
}

class _ParentScreenState extends State<ParentScreen> {
  int parentTaps = 0;

  @override
  Widget build(BuildContext context) {
    debugPrint('🟦 ParentScreen build');
    return Scaffold(
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () => setState(() => parentTaps++),
            child: Text('Parent taps: $parentTaps'),
          ),
          const CounterBox(label: 'A'),                              // const: same instance every time
          CounterBox(label: 'B', parentTaps: parentTaps),            // new instance every time
          const StaticBadge(),                                       // const stateless
        ],
      ),
    );
  }
}

class CounterBox extends StatefulWidget {
  const CounterBox({super.key, required this.label, this.parentTaps = 0});
  final String label;
  final int parentTaps;
  @override
  State<CounterBox> createState() => _CounterBoxState();
}

class _CounterBoxState extends State<CounterBox> {
  int taps = 0;

  @override
  void didUpdateWidget(CounterBox old) {
    super.didUpdateWidget(old);
    debugPrint('🟧 ${widget.label} didUpdateWidget');
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('🟩 ${widget.label} build');
    return ElevatedButton(
      onPressed: () => setState(() => taps++),
      child: Text('${widget.label}: $taps (parent: ${widget.parentTaps})'),
    );
  }
}

class StaticBadge extends StatelessWidget {
  const StaticBadge({super.key});
  @override
  Widget build(BuildContext context) {
    debugPrint('⬜ StaticBadge build');
    return const Text('I never change');
  }
}

What the console prints

You tapConsole outputWhy
App startsParentScreen build, A build, B build, StaticBadge buildFirst mount: every Element is created and built once.
Button AA buildOnly A's Element is dirty. The walk starts there and goes down. The parent is untouched.
Button BB buildSame reason. Siblings and parent are not involved.
Button ParentParentScreen build, B didUpdateWidget, B buildParent is dirty. Its new build creates a new B widget, same type and key, so B's Element is reused and updated. A and StaticBadge are the same const instances, so they are skipped. B's taps keeps its value because its State survived.
ParentScreen (Stateful)       ← setState() here
└─ Scaffold ............... rebuilt
   └─ Column .............. rebuilt
      ├─ ElevatedButton ... rebuilt
      ├─ CounterBox A ..... SKIPPED (const, same instance)
      ├─ CounterBox B ..... update() → didUpdateWidget → build (State kept)
      └─ StaticBadge ...... SKIPPED (const, same instance)

Now the same walk when A calls its own setState:

ParentScreen ................ not dirty, not visited
└─ Scaffold / Column ....... not visited
   └─ CounterBox A ......... dirty ← setState() here
      └─ ElevatedButton ..... rebuilt (its own subtree only)

Every scenario in one table

ScenarioParent builds?Child builds?Child's State
Child calls its own setStateNoYes, its subtree onlyKept, value changed
Parent setState, child is constYesNoUntouched
Parent setState, child is a stored instance (final _child = ...)YesNo (same instance)Untouched
Parent setState, child is a new non-const instanceYesYes, via didUpdateWidgetKept
Parent setState, child's key or type changedYesYes, a new oneDestroyed and recreated
An InheritedWidget the child reads changed (Theme, MediaQuery)NoYes, even if constKept
const is not a force field A const child skips parent-triggered rebuilds only. If it reads an InheritedWidget through context, it still rebuilds when that data changes. That is why const Text('hi') still follows a theme change.
Reset a State on purpose Give the child a key that changes: CounterBox(key: ValueKey(userId), ...). A new key fails canUpdate, so the old Element and State are discarded and a fresh State starts with its initial values.

Controlling rebuild scope in real apps

The rules above give you these practical tools. Use them in this order: the first two are free.

TechniqueHow it limits rebuildsUse when
1. const constructorsIdentical instance, so updateChild skips it.Always, wherever the arguments are compile-time constants. Turn on prefer_const_constructors.
2. Extract a widget classGets its own Element, can be const, and can own its own setState.A big build where only one part changes.
3. Move state downPut the setState in the smallest widget that needs the data.A counter or toggle that lives inside a large screen.
4. The child parameterBuilders such as AnimatedBuilder keep your static child as one instance.Animations over a heavy subtree.
5. ValueListenableBuilder / ListenableBuilderRebuilds only its builder when a notifier changes.A single value changes often (progress, timer).
6. StatefulBuilderA local setState scope inside a stateless place (a dialog).Small, throwaway state.
7. State management selectorsBlocBuilder.buildWhen, BlocSelector, context.select.Shared app state. See Prep #6 on BLoC.

Helper method vs widget class

Dart · extract, do not helper-method
// ❌ helper method: runs inside the parent's build, returns a NEW widget every time,
//    so it can never be skipped. It also cannot be const or keep its own state.
Widget _buildHeader() => Text('Dashboard $_count');

// ✅ extracted class: its own Element, const-able, skipped when its inputs are identical
class Header extends StatelessWidget {
  const Header({super.key});
  @override
  Widget build(BuildContext context) => const Text('Dashboard');
}

The child parameter pattern

Dart · child parameter
AnimatedBuilder(
  animation: _controller,
  child: const HeavyChart(),                   // built ONCE, same instance on every tick
  builder: (context, child) => Transform.rotate(
    angle: _controller.value * 6.28,
    child: child,                                // reused, so updateChild skips it
  ),
)

Rebuild only a number

Dart · ValueListenableBuilder
final _progress = ValueNotifier<double>(0);      // dispose it in dispose()

ValueListenableBuilder<double>(
  valueListenable: _progress,
  builder: (context, value, child) => Text('${(value * 100).round()}%'),
)                                                // only this builder reruns, never the parent
Measure before you optimise Rebuilding is cheap in Flutter. Do not split every widget on a hunch. Open DevTools → Performance and enable the rebuild/track-widget-rebuilds tools to see what really rebuilds, then fix the hot spots.

Which one to use, and what each can do

CapabilityStatelessWidgetStatefulWidget
Holds data between rebuildsNoYes, in the State
Can call setStateNoYes
Has initState / disposeNoYes
Can own controllers (animation, text, focus, scroll)NoYes, and must dispose them
Reacts to InheritedWidget changesYesYes (didChangeDependencies)
Receives new config from parentYes (rebuilds)Yes (didUpdateWidget then build)
CostOne objectWidget + State + a bit more bookkeeping (still tiny)

A simple decision rule

Ask two questions in order:

1. Does a value change while this widget is on screen? If no, use StatelessWidget. 2. Does only this widget (and its children) care about the value? If yes, it is ephemeral state and belongs in a State. If other screens or distant widgets need it, it is app state: lift it up or use a state management solution (Provider, BLoC, Riverpod).

Ephemeral state (use a State)App state (lift it up)
Current tab or page index, a checkbox, an expanded/collapsed flag.Logged-in user, cart, settings, feature flags.
AnimationController, TextEditingController, FocusNode, ScrollController, PageController.Data from an API that several screens show.
A form's local draft before submission.Anything that must survive leaving the screen.

Deprecated things you will meet, and why they changed

First, a clarification: StatelessWidget and StatefulWidget are not deprecated. They are core widgets in package:flutter/widgets.dart and will stay. What gets deprecated are the APIs around them: buttons, theming helpers and design-system classes.

How a deprecation works

Flutter follows its compatibility policy: a class or member is annotated with @Deprecated('Use X instead. This feature was deprecated after v3.N'), it keeps working for a while with an analyzer warning, then it is removed in a later release. The message always names the replacement. Most renames can be fixed automatically:

shell
dart fix --dry-run     # preview the automatic fixes
dart fix --apply       # apply them
flutter analyze        # check what is left

Common ones and the reason behind each

OldNewWhy it changed
FlatButton, RaisedButton, OutlineButton (removed)TextButton, ElevatedButton, OutlinedButtonOld buttons had fixed styling and many one-off properties. New ones are styled through a single ButtonStyle, so themes work consistently.
WillPopScopePopScopeAndroid predictive back must know before the gesture whether back will be handled. The old callback was async and answered too late. PopScope takes a plain canPop boolean.
MaterialStateProperty and friendsWidgetStateProperty and friendsHover, pressed and focused states are not Material-only. The generic name lets core widgets use them.
color.withOpacity(0.5)color.withValues(alpha: 0.5)withOpacity rounded alpha to 8 bits. Flutter now supports wide-gamut colors, so the new method keeps precision.
textScaleFactortextScalerModern Android scales text non-linearly. A single number cannot describe that, a TextScaler object can.
Scaffold.of(context).showSnackBarScaffoldMessenger.of(context).showSnackBarA messenger above the Scaffold keeps a snackbar alive across route changes.
Bundled package:flutter/material.dart and cupertino.dartpackage:material_ui and package:cupertino_uiDesign libraries were tied to quarterly SDK releases. As packages they can ship fixes on their own schedule. Formally deprecated in Flutter 3.50.
Dart · PopScope
// WillPopScope  ->  PopScope
PopScope(
  canPop: false,
  onPopInvokedWithResult: (didPop, result) {
    if (didPop) return;
    // show your "discard changes?" dialog here
  },
  child: const MyForm(),
)
The big one in Flutter 3.50 Material and Cupertino code was frozen in 3.44, version 1.0 of the standalone packages arrived in 3.47, and the in-framework libraries were formally deprecated in 3.50 (11 November 2026). Your widget code does not change, only the imports. Class names stay the same.
shell · 3.50 migration
# 1. automatic migration of imports
dart fix --apply --code=migrate_design_widgets

# 2. if the packages were not added to pubspec.yaml
flutter pub add material_ui
flutter pub add cupertino_ui
Dart · imports
// before
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

// after
import 'package:material_ui/material_ui.dart';
import 'package:cupertino_ui/cupertino_ui.dart';

Two practical details from the migration guide. If a third-party package still imports the old libraries, wrap your app in MaterialUiCompatibilityBridge (temporary, it is deprecated by design) so theme and localizations still reach it. And if you use flutter_localizations, remove its import where it clashes with the new packages, or use show GlobalWidgetsLocalizations, to avoid an ambiguous_import error.

Common mistakes and the fix

MistakeWhat goes wrongFix
One big setState at the screen root.Whole subtree is diffed on every keystroke or tick.Move state down, extract widgets, add const.
Creating controllers inside build.A new controller on every rebuild: leaks and lost state.Create in initState or a late final field, free in dispose.
Forgetting dispose.Controllers, streams and timers keep running after the screen is gone.Every AnimationController, TextEditingController, FocusNode, StreamSubscription and Timer needs a matching cleanup.
setState after an await without a check.Crash if the user already left the screen.if (!mounted) return; first.
Storing derived data in State.Two sources of truth that drift apart.Compute it inside build from the real source.
Using a helper method for a big subtree.Cannot be skipped, cannot be const.Extract a widget class.
Expecting const to block Theme changes.Confusing “why did my const widget rebuild?”.It rebuilds because it depends on an InheritedWidget. That is correct behavior.
Using GlobalKey to call a child's setState.Tight coupling and fragile code.Pass data and callbacks down, or use a proper state solution.

Test it: why pump() matters

Because setState only schedules a frame, tests must run that frame. tester.pump() does exactly that.

Dart · widget test
testWidgets('tapping A changes only A', (tester) async {
  await tester.pumpWidget(const MaterialApp(home: ParentScreen()));

  await tester.tap(find.textContaining('A: 0'));
  await tester.pump();                       // runs the frame that setState scheduled

  expect(find.textContaining('A: 1'), findsOneWidget);
  expect(find.textContaining('B: 0'), findsOneWidget);   // sibling untouched
});

Interview answers

Why does StatefulWidget need two classes?

Widgets are immutable and recreated on every build, so they cannot hold data that must survive. The mutable data goes into a separate State object that the Element keeps alive. The widget is configuration, the State is memory.

What does setState actually do?

It runs the callback synchronously, then calls markNeedsBuild on its Element. That adds the Element to the dirty list and schedules a frame. The rebuild happens at the next frame, not inside setState.

Does setState rebuild the whole screen?

No. It marks only the calling State's Element dirty. The rebuild walks down from there, and each child is skipped if the new widget is the identical instance (const or cached).

Parent calls setState. Does a nested stateful child lose its state?

No. If the new child has the same type and key, canUpdate is true, so the Element and State are reused. Flutter calls didUpdateWidget and rebuilds it. State is lost only if the key or type changes.

Why is const useful here?

A const widget is the same instance every time, so updateChild sees child.widget == newWidget and skips the whole subtree. It still rebuilds if it depends on an InheritedWidget that changed.

What is the difference between extends and implements for widgets?

extends inherits the whole implementation (Element creation, keys, diagnostics) and you only write build. implements inherits nothing, so you would rewrite every member. Use extends for the widget type and implements to add an interface such as PreferredSizeWidget.

Why was WillPopScope deprecated?

Android predictive back needs a synchronous answer before the gesture starts. WillPopScope used an async callback. PopScope uses a canPop flag plus onPopInvokedWithResult.

Final verdict

Use StatelessWidget by default, and make it const whenever you can. Reach for StatefulWidget only when a value changes while the widget is on screen and only that widget cares. Keep the setState as low in the tree as possible, never put data in the widget, always dispose what the State creates, and remember the three facts: the dirty flag is per Element, the rebuild walks down, and an identical instance stops the walk. If you want proof in your own app, run the demo above and watch the console.

Sources: State.setState · StatefulWidget · Inside Flutter · Ephemeral vs app state · Material and Cupertino migration guide · Breaking changes index · material_ui

Related in this series: Flutter Prep #6 How BLoC actually works · Flutter Prep #16 Dio vs http

Nachiketa Pandey
// written by

Nachiketa Pandey

Senior Flutter Developer · Cross-Platform & Fintech Applications

Building production Flutter apps at Kotak Neo — clean architecture, BLoC, agentic AI integrations, and fintech-grade security. Sharing everything I learn, one post at a time.

Flutter & Dart Clean Architecture BLoC Firebase FinTech
View Full Portfolio

Comments

↑
Nachiketa
Meet Author// tap to open
▶