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.
The short answer
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.
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 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.
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.
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.
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.
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
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.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
| Piece | What it does | Why it exists |
|---|---|---|
extends StatelessWidget | Inherits createElement(), key handling and diagnostics. | You only fill in the one blank the framework cannot guess: build. |
const constructor | Lets callers write const GreetingCard(...). | A const instance is created once and reused, so Flutter can skip it on rebuilds. |
super.key | Passes the optional key to Widget. | Keys control Element reuse (see the rebuild section). |
final fields | Hold 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 can | You 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.
StatefulWidget, from A to Z
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.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.
| Object | Lives for | Holds |
|---|---|---|
Counter (widget) | One build. Replaced on every parent rebuild. | Configuration such as step. |
_CounterState | From mount until the Element leaves the tree. | Mutable data, controllers, subscriptions. |
StatefulElement | While the same type and key sit at that spot. | Current widget + the State. |
The parts of a State, explained
| Piece | Meaning |
|---|---|
State<Counter> | The generic bound T extends StatefulWidget gives you a correctly typed widget getter. Without it, widget.step would not compile. |
widget | Always the newest configuration. When the parent rebuilds, Flutter swaps it in and calls didUpdateWidget. |
context | The Element of this State. It is the same object for the State's whole life. |
mounted | true 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:
| Hook | setState needed? | Note |
|---|---|---|
initState | No | Set fields directly. The first build follows anyway. |
didChangeDependencies | No | A build follows. Use it when an InheritedWidget you read changes. |
didUpdateWidget(old) | No | Compare old with widget, update fields. A build follows automatically. |
build | Never call it here | Calling setState inside build throws an error. |
dispose | Never call it here | Release 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.
| Keyword | Meaning | Flutter example | Why this choice |
|---|---|---|---|
extends | Inherit the full implementation. One parent only. | class A extends StatelessWidget | You get createElement, keys and diagnostics for free and only write build. |
implements | Promise to provide every member yourself. No code is inherited. | implements PreferredSizeWidget | Good for adding a capability (an interface). Using it instead of extends on a widget would force you to rewrite the whole Widget class. |
with | Mix in reusable code from a mixin. Many allowed. | with SingleTickerProviderStateMixin | Shares 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. |
abstract | Cannot be instantiated. Subclasses must fill the blanks. | StatelessWidget, StatefulWidget | Forces 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.
// 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
| Class | Extends | Element it creates | Used for |
|---|---|---|---|
StatelessWidget | Widget | StatelessElement | Compose other widgets, no memory. |
StatefulWidget | Widget | StatefulElement | Compose + memory + setState. |
InheritedWidget | ProxyWidget | InheritedElement | Share data down the tree (Theme, MediaQuery, Provider). |
RenderObjectWidget | Widget | RenderObjectElement | Leaf 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:
// 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.
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
| Rule | What 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. |
// ❌ 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.
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.
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.
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:
// 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.
// 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 tap | Console output | Why |
|---|---|---|
| App starts | ParentScreen build, A build, B build, StaticBadge build | First mount: every Element is created and built once. |
| Button A | A build | Only A's Element is dirty. The walk starts there and goes down. The parent is untouched. |
| Button B | B build | Same reason. Siblings and parent are not involved. |
| Button Parent | ParentScreen build, B didUpdateWidget, B build | Parent 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
| Scenario | Parent builds? | Child builds? | Child's State |
|---|---|---|---|
Child calls its own setState | No | Yes, its subtree only | Kept, value changed |
Parent setState, child is const | Yes | No | Untouched |
Parent setState, child is a stored instance (final _child = ...) | Yes | No (same instance) | Untouched |
Parent setState, child is a new non-const instance | Yes | Yes, via didUpdateWidget | Kept |
Parent setState, child's key or type changed | Yes | Yes, a new one | Destroyed and recreated |
| An InheritedWidget the child reads changed (Theme, MediaQuery) | No | Yes, even if const | Kept |
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.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.
| Technique | How it limits rebuilds | Use when |
|---|---|---|
1. const constructors | Identical instance, so updateChild skips it. | Always, wherever the arguments are compile-time constants. Turn on prefer_const_constructors. |
| 2. Extract a widget class | Gets its own Element, can be const, and can own its own setState. | A big build where only one part changes. |
| 3. Move state down | Put the setState in the smallest widget that needs the data. | A counter or toggle that lives inside a large screen. |
4. The child parameter | Builders such as AnimatedBuilder keep your static child as one instance. | Animations over a heavy subtree. |
5. ValueListenableBuilder / ListenableBuilder | Rebuilds only its builder when a notifier changes. | A single value changes often (progress, timer). |
6. StatefulBuilder | A local setState scope inside a stateless place (a dialog). | Small, throwaway state. |
| 7. State management selectors | BlocBuilder.buildWhen, BlocSelector, context.select. | Shared app state. See Prep #6 on BLoC. |
Helper method vs widget class
// ❌ 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
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
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 parentWhich one to use, and what each can do
| Capability | StatelessWidget | StatefulWidget |
|---|---|---|
| Holds data between rebuilds | No | Yes, in the State |
Can call setState | No | Yes |
Has initState / dispose | No | Yes |
| Can own controllers (animation, text, focus, scroll) | No | Yes, and must dispose them |
| Reacts to InheritedWidget changes | Yes | Yes (didChangeDependencies) |
| Receives new config from parent | Yes (rebuilds) | Yes (didUpdateWidget then build) |
| Cost | One object | Widget + 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:
dart fix --dry-run # preview the automatic fixes
dart fix --apply # apply them
flutter analyze # check what is leftCommon ones and the reason behind each
| Old | New | Why it changed |
|---|---|---|
FlatButton, RaisedButton, OutlineButton (removed) | TextButton, ElevatedButton, OutlinedButton | Old buttons had fixed styling and many one-off properties. New ones are styled through a single ButtonStyle, so themes work consistently. |
WillPopScope | PopScope | Android 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 friends | WidgetStateProperty and friends | Hover, 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. |
textScaleFactor | textScaler | Modern Android scales text non-linearly. A single number cannot describe that, a TextScaler object can. |
Scaffold.of(context).showSnackBar | ScaffoldMessenger.of(context).showSnackBar | A messenger above the Scaffold keeps a snackbar alive across route changes. |
Bundled package:flutter/material.dart and cupertino.dart | package:material_ui and package:cupertino_ui | Design libraries were tied to quarterly SDK releases. As packages they can ship fixes on their own schedule. Formally deprecated in Flutter 3.50. |
// WillPopScope -> PopScope
PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, result) {
if (didPop) return;
// show your "discard changes?" dialog here
},
child: const MyForm(),
)# 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// 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
| Mistake | What goes wrong | Fix |
|---|---|---|
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.
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
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.
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.
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).
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.
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.
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.
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

Comments
Post a Comment