Skip to main content
Guide · Performance

Flutter Bug Fixing Guide: How to Diagnose Crashes, Memory Leaks & Platform Channel Errors

The workflow I use to diagnose and fix Flutter bugs in production apps: crash reporting setup, reading common Flutter errors, hunting memory leaks in DevTools, and fixing platform channel and native build failures.

Afaq Zahir, author

Afaq Zahir

Flutter mobile product engineer

Published Updated 8 min read

On this page
  1. What is the fastest way to fix a Flutter bug?
  2. How do you set up crash reporting in Flutter?
  3. How do you read the most common Flutter errors?
  4. How do you find memory leaks with Flutter DevTools?
  5. Symptom, cause and fix at a glance
  6. How do you make sure a bug stays fixed?
  7. Frequently Asked Questions
  8. Stuck on a bug you cannot reproduce?

Quick answer

Fix Flutter bugs with a repeatable workflow: reproduce the bug on a real device in the same build mode, read the logs and crash report stack trace, isolate the cause to one widget, state change or native bridge, apply the smallest fix that addresses the root cause, and add a regression test so it cannot come back.

Key takeaways

  • Set up Crashlytics or Sentry before launch; a symbolicated stack trace from production saves hours of guessing.
  • Most Flutter errors have a known shape: RenderFlex overflow, setState after dispose, null check failures, MissingPluginException and native build failures each have standard fixes.
  • Use the DevTools Memory tab to find undisposed controllers, stream subscriptions and oversized images.
  • Reproduce release-only bugs in profile or release mode, since debug mode behaves differently.
  • Every fixed bug should leave behind a unit, widget or integration test.

Bugs in a mobile app cost more than bugs on the web: users cannot refresh, they leave a one-star review, and your fix waits on store review. In 4+ years of shipping Flutter apps, I have learned that fixing bugs quickly is less about cleverness and more about a repeatable process. This is the workflow I use, the tooling I set up before launch, and the Flutter errors I see most often with their fixes.

What is the fastest way to fix a Flutter bug?

The fastest way is a fixed triage workflow: reproduce, read the logs, isolate, fix, and add a regression test. Skipping straight to "fixing" without a reliable reproduction is the most common reason a bug comes back.

  1. Reproduce. Get the bug to happen on demand, on a real device, in the same build mode the user had. Many bugs only appear in release mode, on older Android devices, or with a slow network. Note the device, OS version, app version and exact steps.
  2. Read the logs. Pull the full stack trace from your crash reporter or flutter logs. Read from the first line that points into your own code, not the framework frames at the top.
  3. Isolate. Narrow the cause to one widget, one state change, one API response or one native call. Commenting out half the screen, or reproducing the case in a small widget test, is often faster than reading code.
  4. Fix the root cause. Make the smallest change that removes the cause, not the symptom. Wrapping a crash in try/catch so it goes quiet is not a fix.
  5. Add a regression test. Write a unit, widget or integration test that fails before the fix and passes after it. Then ship, and watch the crash reporter for that issue over the next release.

How do you set up crash reporting in Flutter?

Use Firebase Crashlytics or Sentry, and hook both Flutter framework errors and uncaught asynchronous errors. Without crash reporting, production bugs reach you as vague user complaints instead of stack traces.

Firebase Crashlytics

Crashlytics is free and a natural fit if you already use Firebase. After adding firebase_crashlytics and running flutterfire configure, register the error handlers in main():

import 'dart:ui';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  // Errors thrown inside the Flutter framework (build, layout, paint).
  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;

  // Uncaught async errors that never reach the framework.
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  runApp(const MyApp());
}

Two details matter. If you build with --obfuscate --split-debug-info, upload the debug symbols or your Dart stack traces will be unreadable. And set a user identifier with setUserIdentifier (a non-personal ID) so you can match a crash to a support ticket.

Sentry

Sentry works without Firebase, adds performance tracing and breadcrumbs, and suits teams that already use it on the backend:

import 'package:sentry_flutter/sentry_flutter.dart';

Future<void> main() async {
  await SentryFlutter.init(
    (options) {
      options.dsn = const String.fromEnvironment('SENTRY_DSN');
      options.tracesSampleRate = 0.2;
    },
    appRunner: () => runApp(const MyApp()),
  );
}

Pick one. Running both doubles your SDK footprint and your privacy disclosures, which matter for store review (see my guide on fixing App Store and Google Play rejections).

How do you read the most common Flutter errors?

Most Flutter errors fall into a handful of known types, and the error message usually tells you exactly which one. Here are the ones I fix most often.

RenderFlex overflowed

"A RenderFlex overflowed by 42 pixels on the right" means a Row or Column has children larger than the space available. It shows as yellow and black stripes in debug mode and as clipped content in release. It often appears only on small screens or with large system font sizes.

// Before: long text pushes the icon off screen
Row(children: [Text(title), const Icon(Icons.chevron_right)]);

// After: let the text take the remaining space and truncate
Row(children: [
  Expanded(child: Text(title, overflow: TextOverflow.ellipsis)),
  const Icon(Icons.chevron_right),
]);

Test with the largest accessibility font size on a small device before every release; it catches most of these.

setState() called after dispose()

This happens when an async call completes after the user has left the screen, and the code then calls setState on a widget that no longer exists. Check mounted after every await before touching state or context:

Future<void> _load() async {
  final items = await repository.fetchItems();
  if (!mounted) return;
  setState(() => _items = items);
}

If this error shows up a lot, it is a sign that business logic lives in widgets. Moving it into a view model or state management layer fixes the whole class of bug; I cover that in why MVVM matters in Flutter.

Null check operator used on a null value

This comes from a ! on something that was null at runtime: a missing JSON field, a GlobalKey whose currentState is not mounted yet, or a value read before it was loaded. The fix is almost never another !. Model the field as nullable and handle the null case, or give it a safe default when parsing:

// Before
final name = json['name']!;

// After
final name = json['name'] as String? ?? 'Unknown';

MissingPluginException

"MissingPluginException(No implementation found for method X on channel Y)" means Dart called a platform channel that has no native handler registered. The usual causes: you added a plugin and used hot reload or hot restart instead of a full rebuild, the plugin does not support the current platform, or the channel name differs between Dart and native code. Stop the app, run flutter clean, rebuild, and confirm the plugin supports the platform. For your own channels, keep the channel name in one constant and handle PlatformException:

const _channel = MethodChannel('com.example.app/battery');

Future<int?> batteryLevel() async {
  try {
    return await _channel.invokeMethod<int>('getBatteryLevel');
  } on PlatformException catch (e, stack) {
    FirebaseCrashlytics.instance.recordError(e, stack);
    return null;
  }
}

Gradle and CocoaPods build failures

Native build failures are usually version mismatches, not code bugs. On Android, read the first error in the Gradle output, not the last; common causes are an Android Gradle Plugin, Kotlin or Java version that a plugin does not support, or a minSdk lower than a plugin requires. On iOS, CocoaPods failures usually come from a stale Podfile.lock or an iOS deployment target lower than a pod requires. My reset sequence for iOS is:

flutter clean
flutter pub get
cd ios
rm -rf Pods Podfile.lock
pod install --repo-update

Then raise the platform :ios version in the Podfile if a pod asks for it. Upgrade dependencies one at a time so you know which one broke the build.

How do you find memory leaks with Flutter DevTools?

Use the Memory view in DevTools on a profile build: take a snapshot, open and close the suspect screen several times, take another snapshot, and compare. Objects that keep growing after the screen is closed are leaking.

The step-by-step routine I use:

  1. Run the app with flutter run --profile on a real device and open DevTools.
  2. In the Memory view, force a garbage collection and take a heap snapshot.
  3. Navigate into the screen you suspect and back out, five or ten times.
  4. Force garbage collection again and take a second snapshot, then use the diff view.
  5. Look for your own classes (screen states, view models, controllers) whose instance count grows with each visit. Inspect their retaining path to see what is holding them.

The usual culprits are AnimationController, TextEditingController, ScrollController and StreamSubscription objects that are never disposed, listeners added to a long-lived object and never removed, and large images decoded at full resolution. Clean up everything you create in dispose():

@override
void dispose() {
  _animationController.dispose();
  _searchController.dispose();
  _subscription.cancel();
  _cart.removeListener(_onCartChanged);
  super.dispose();
}

For images, pass cacheWidth or cacheHeight to Image.network so a 4000-pixel photo is not decoded at full size for a thumbnail. On LQDCNVS, where the app streams 4K artwork on phones and TV devices, being careful about decoded image size and disposing controllers between screens mattered far more on low-memory TV hardware than on phones. More on rendering cost in my Flutter performance tips.

Symptom, cause and fix at a glance

When a bug report comes in, this table is usually where I start.

SymptomLikely causeFix
Yellow and black stripes, clipped textRenderFlex overflow in a Row or ColumnWrap flexible children in Expanded or Flexible, make content scrollable
"setState() called after dispose()"Async work finishing after the screen closedCheck mounted after each await; move logic out of widgets
"Null check operator used on a null value"! on missing dataNullable types with defaults or explicit null handling
MissingPluginExceptionPlugin not registered, unsupported platform, or name mismatchFull rebuild after flutter clean, verify platform support and channel names
Android build fails after a package updateGradle, Kotlin, Java or minSdk mismatchRead the first Gradle error, align versions, upgrade one package at a time
iOS build fails at pod installStale Pods or low deployment targetDelete Pods and Podfile.lock, pod install --repo-update, raise target
App slows down or is killed after long useMemory leak from undisposed objects or large imagesDevTools snapshot diff, dispose controllers, set cacheWidth
Works in debug, crashes in releaseObfuscation, missing ProGuard/R8 rules, or debug-only assertions hiding issuesReproduce in --release, add keep rules, read the symbolicated trace
UI stutters during scrollingHeavy work in build or on the main isolateProfile in DevTools, move parsing to Isolate.run(), use builders

How do you make sure a bug stays fixed?

Write a test that reproduces the bug before you fix it, and keep it in the suite. A widget test is often enough for UI bugs such as overflows:

testWidgets('product tile does not overflow with long titles', (tester) async {
  tester.view.physicalSize = const Size(320, 640);
  tester.view.devicePixelRatio = 1.0;
  addTearDown(tester.view.reset);

  await tester.pumpWidget(const MaterialApp(
    home: Scaffold(body: ProductTile(title: 'A very long product title that used to overflow')),
  ));

  expect(tester.takeException(), isNull);
});

Logic bugs belong in plain unit tests against your view models or repositories, which is another reason to keep logic out of widgets. Flows that cross a platform channel or a real backend need integration tests on a device.

Frequently Asked Questions

Why does my Flutter app work in debug mode but crash in release?

Debug and release builds behave differently. Release builds are compiled ahead of time, can be obfuscated, and on Android are shrunk by R8, which can remove classes a plugin loads by reflection. Reproduce with flutter run --release, check the native logs, and add keep rules if a class is being stripped.

Should I use Crashlytics or Sentry for Flutter?

If your app already uses Firebase, Crashlytics is free and integrates in minutes. Sentry is a strong choice if you are not on Firebase, want performance tracing alongside errors, or already use it for your backend. Either is far better than none; pick one and set it up before launch.

How do I find which widget is causing a RenderFlex overflow?

The error in the console names the widget and includes the creation location if you are in debug mode. Open the Widget Inspector in DevTools and select the striped area to jump to the widget. Then check its parent constraints; the fix is usually Expanded, Flexible or a scroll view.

Is calling flutter clean a real fix?

Sometimes. It fixes problems caused by stale build artifacts, such as MissingPluginException after adding a plugin or odd behaviour after switching branches. If the error returns after a clean build, the cause is in your configuration or code, and you need to read the actual error instead of cleaning again.

How long does it take to fix a typical Flutter bug?

It depends almost entirely on how easy the bug is to reproduce. A bug with a clear stack trace and reproduction steps is often fixed within hours. Intermittent bugs, release-only crashes and native build issues can take days. Good crash reporting and logs shorten that time more than anything else.

Stuck on a bug you cannot reproduce?

If your Flutter app has crashes you cannot track down, memory problems, or a build that stopped compiling after an upgrade, I can help diagnose and fix it. See my Flutter bug fixing and maintenance service or get in touch.

Afaq Zahir

Written by

Afaq Zahir

Flutter mobile product engineer with 4+ years shipping 20+ apps to the App Store and Google Play. Led Flutter teams at Metasense and Apptex.

GitHub ↗LinkedIn ↗Last reviewed
Book a call