Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 73 ยท Practice and review

Common Flutter Mistakes and How to Fix Them

Fix the Flutter errors everyone hits: RenderFlex overflow, unbounded height, setState after dispose, BuildContext across async gaps and rebuild storms.

Most Flutter bugs fall into a short list. The red-and-yellow overflow stripes, the "Vertical viewport was given unbounded height" wall of text, the crash after a screen closes: every Flutter developer meets them in the first month. They look scary, but each has a simple cause, and once you know the cause the fix takes a minute.

This lesson walks through the most common mistakes, shows the failing code, explains why it fails, and gives the fix. Many of the explanations rest on one idea from constraints and layout: a parent gives its child constraints, the child picks a size inside them, and the parent positions it.

Real vs stand-in. The Flutter code is real and read-only on this site. The live examples are JavaScript stand-ins that reproduce the mechanics (constraint solving, lifecycle flags, rebuild counting), so you can see the rule behind each error. They do not run Flutter.

Five families of mistakes

Layout Overflow and unbounded sizes.
Lifecycle Work after dispose.
Context Using it across an await.
Rebuilds Too many, too wide.
1 / 2

1. RenderFlex overflowed

DART
Row(
  children: [
    const Icon(Icons.person),
    Text('A very long name that does not fit on a small phone screen at all'),
  ],
)

You see yellow-and-black stripes and "A RenderFlex overflowed by 143 pixels on the right."

Why. A Row gives non-flex children unbounded width along its main axis and then lays them out in a line. The Text takes all the width it wants, and the total is wider than the screen.

Fix. Make the text flexible, so it receives the leftover width:

DART
Row(
  children: [
    const Icon(Icons.person),
    Expanded(
      child: Text('A very long name that does not fit...', overflow: TextOverflow.ellipsis),
    ),
  ],
)

Use Flexible instead of Expanded when the child may be smaller than the space. For a screen that may be too tall, wrap the content in a SingleChildScrollView (the keyboard often causes vertical overflow). See Row, Column and Flex.

Reproduce the rule

JS Stand-in: why Expanded fixes the overflow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first call the text keeps its natural width of 460, so the row overflows by 164. In the second, the flexible child is limited to the 296 pixels left.

2. Unbounded height or width

DART
Column(
  children: [
    const Text('Messages'),
    ListView(children: messages),   // crash
  ],
)

The error reads "Vertical viewport was given unbounded height."

Why. A Column gives its children unbounded height. A ListView wants to be as tall as the space it gets, but "all of infinity" is not a size, so Flutter stops.

Fix. Tell the list how much room it has:

DART
Column(
  children: [
    const Text('Messages'),
    Expanded(child: ListView(children: messages)),
  ],
)

If the list is small and should be as tall as its content, use shrinkWrap: true, but only for short lists, because it lays out every item and removes laziness. The same family of errors appears with a Row inside a Row, a TextField in a Row ("An InputDecorator... cannot have an unbounded width"), and a Spacer in a scroll view. The cure is always the same: give the child a bounded size with Expanded, SizedBox or ConstrainedBox. See ListView, GridView and slivers.

3. A widget that ignores its width and height

DART
Center(child: Container(width: 300, height: 300, color: Colors.red))   // in a 100x100 parent

Why. Sizes are requests clamped to constraints. If the parent gave tight 100ร—100 constraints, 300 is not allowed.

Fix. Change the parent's constraints (not the child's number), or loosen them with Align, Center or UnconstrainedBox. Use LayoutBuilder to see what you actually receive.

4. setState called after dispose

DART
Future<void> _load() async {
  final data = await api.fetch();
  setState(() => _items = data);      // may throw
}

The message is "setState() called after dispose()" (or "This widget has been unmounted").

Why. await pauses the function. If the user leaves the screen during the wait, Flutter disposes the State, and when the function resumes it touches a dead object.

Fix. Check mounted after every await that precedes setState, and cancel what you can in dispose:

DART
Future<void> _load() async {
  final data = await api.fetch();
  if (!mounted) return;
  setState(() => _items = data);
}

@override
void dispose() {
  _timer?.cancel();
  _subscription?.cancel();
  _controller.dispose();
  super.dispose();
}

Controllers, Timers, StreamSubscriptions, FocusNodes, AnimationControllers and TextEditingControllers all need disposal. See StatefulWidget and setState.

JS Stand-in: a lifecycle with and without the mounted check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

5. Using BuildContext across async gaps

DART
onPressed: () async {
  await saveProfile();
  Navigator.of(context).pop();           // lint: use_build_context_synchronously
  ScaffoldMessenger.of(context).showSnackBar(...);
}

Why. A BuildContext is a position in the tree. After an await, that position may no longer exist (the widget could have been removed or moved), and looking things up from it gives wrong results or errors.

Fix. In a State, check mounted after the await. In a StatelessWidget, use context.mounted. Or grab what you need before awaiting:

DART
onPressed: () async {
  final navigator = Navigator.of(context);
  final messenger = ScaffoldMessenger.of(context);
  await saveProfile();
  navigator.pop();
  messenger.showSnackBar(const SnackBar(content: Text('Saved')));
}

The analyzer lint use_build_context_synchronously catches this; do not silence it. See BuildContext and InheritedWidget.

6. Creating the Future inside build

DART
Widget build(BuildContext context) {
  return FutureBuilder(
    future: fetchUser(),          // new request on EVERY rebuild
    builder: ...,
  );
}

Why. build can run many times per second (animations, keyboard, parent rebuilds). Each run starts a new request, so the spinner flickers and the server gets hammered.

Fix. Create the future once in initState, or use a state-management layer that caches it. See FutureBuilder and StreamBuilder.

7. Rebuild storms

Symptoms: a whole screen rebuilds when one counter changes; animations stutter; the profiler shows the same widgets rebuilding dozens of times.

Common causes and fixes:

  • setState too high. Calling it in a big page rebuilds everything below. Move the changing part into its own small widget, so only it rebuilds.
  • Missing const. A const widget is created once and skipped when its parent rebuilds. Add const wherever the analyzer allows.
  • Watching too much. With Provider, context.watch<Cart>() rebuilds on every change; use context.select for one field, or read in callbacks (Provider).
  • Heavy work in build. Sorting a big list or parsing JSON inside build repeats on every rebuild; compute it in state or once.
  • Animating a big subtree. Pass the unchanging part as child to AnimatedBuilder, so only the animated wrapper rebuilds.
JS Stand-in: counting rebuilds with and without small widgets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rebuilding is cheap and normal; only worry when you can measure a problem. Performance and DevTools shows how to find the real hot spots.

8. Other classic slips

  • Forgetting notifyListeners() in a ChangeNotifier: the data changes but the UI does not.
  • Mutating state without setState: _items.add(x) alone changes nothing on screen.
  • Missing keys on reorderable lists: items keep the wrong state after reordering (keys).
  • Using ! on a null value: prefer ?., ?? or a check (null safety).
  • Reading MediaQuery.of(context) too early or in initState: use didChangeDependencies or build.
  • Putting a Scaffold call in the wrong context: ScaffoldMessenger.of(context) needs a context below the MaterialApp.
  • Not testing on a small screen and large text. Test at 1.5ร— or 2ร— text scale.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a ListView directly inside a Column throw an unbounded height error?

    An infinite height is not a size, so the list must be given a bounded one, usually with Expanded.
  2. 2. Which check protects setState after an await?

    mounted becomes false once the State is disposed, so returning early avoids the error.
  3. 3. What is the best fix for FutureBuilder refetching on every rebuild?

    build can run constantly, so the future must be created outside it.
  4. 4. How does const reduce rebuild cost?

    Identical const instances let Flutter skip rebuilding that part of the tree.
  5. 5. A Text overflows inside a Row. Which wrapper gives it the leftover width?

    Expanded (or Flexible) hands the child a bounded width equal to the remaining space.

Summary

  • Overflow and unbounded errors are constraint problems: give flexible children bounded sizes with Expanded, Flexible or SizedBox.
  • After an await, check mounted (or context.mounted) before setState or any context use.
  • Dispose controllers, timers, subscriptions and focus nodes.
  • Create futures once, and keep build free of heavy work.
  • Narrow rebuilds with small widgets, const, and select.

Next: Flutter Interview Questions