Skip to content
  1. Home

Flutter Memory Leaks: How I Tracked Down the Bug That Was Crashing Our App

Telling a product manager you want to stop all new feature development for a solid month is not a conversation anyone looks forward to. I had it anyway, and I was explicit. Our main Flutter app was bleeding performance and user trust and I couldn't see another way to stabilize it. It's still one of the hardest conversations I've ever had, and I'd have it again.

Being a lead mobile developer is mostly not the clean code and smooth animations people picture. A lot more of it is staring at a stack trace at 2 AM, wondering why an app that worked perfectly yesterday is failing at random on staging today, which is how I spent a night last week wrestling with that same app.

It had launched to rave reviews at first. I knew we'd cut corners to get there, though, and the technical debt had been compounding quietly the whole time, waiting for the worst possible moment to collect. That moment turned out to be just before a massive marketing push, when the cracks started showing.

For a while I doubted our entire tech stack. Was Flutter the wrong choice, or were we simply incompetent? After a lot of trial and error the honest answer turned out to be more nuanced than both, since the framework was fine and our approach to it was fundamentally broken.

The four-day 'quick fix'

What finally pushed me into that meeting was a supposedly quick bug fix that took exactly four days. A simple-looking layout issue turned out to be rooted deep in how we managed asynchronous streams across different tabs, and we'd been needlessly rebuilding entire sub-trees of the app sixty times a second.

Using context after an await

Here's the disaster we were dealing with at the start:


// The absolute nightmare way we used to handle things
Future<void> performAction(BuildContext context) async {
  try {
    showLoading(context);
    final result = await apiService.fetchData();
    Navigator.pop(context); // BOOM. Crash if popped early.
    Provider.of<StateStore>(context, listen: false).update(result);
  } catch (e) {
    print('Error: $e');
  }
}

This snippet on its own caused hundreds of phantom crashes. Once an await finishes, the screen that context belongs to may already be gone, so touching it blindly is asking for trouble. A context.mounted check would have stopped the bleeding, but we wanted a fix built into the structure.


// How we handle it safely now
class SafeActionNotifier extends StateNotifier<AsyncValue<Data>> {
  SafeActionNotifier(this._api) : super(const AsyncLoading());

  Future<void> performAction() async {
    state = const AsyncLoading();
    try {
      final result = await _api.fetchData();
      state = AsyncData(result); // Safe UI update
    } catch (e, st) {
      state = AsyncError(e, st);
    }
  }
}

If you're on a recent Riverpod release, StateNotifier is legacy now and AsyncNotifier does the same job. The principle is unchanged. State lives in the notifier, and the widget only reacts to it.

Rules we review against

I used to believe raw coding skill was enough to ship reliable production software. Our app was full of slick algorithms and some properly beautiful animations, and it still began to cave in under its own weight once thousands of users were hitting the servers at the same time, all because the structure holding it up was flawed.

Now we plan for future scale and the brutal edge cases up front. We assume the network will fail at the worst moment, that a frustrated user will tap the same button rapidly and repeatedly, and that the operating system will kill background tasks we depend on. Every layer gets written defensively with that in mind.

Code review is where it's enforced, and it's strict. Sneak raw network logic into a presentation widget and the pull request is rejected. Initial feature development is noticeably slower for it, while long-term maintenance has sped up enormously.

Isolating business logic from UI code is the rule I'd defend hardest, because a bug can then only live on one side of that line. Work this way long enough and building fast, scalable Flutter apps that hold up becomes something you genuinely enjoy.

A few questions worth answering

How do you deal with massive widget classes?

Aggressively. Any build method longer than 50 lines gets its specific visual pieces extracted into their own stateless widgets. Readability improves a lot, and since those pieces are now separate widgets (const where possible), Flutter can skip rebuilding the ones that haven't changed.

Should a big Provider app migrate to Riverpod or Bloc?

Often, if Provider is genuinely limiting you, though plenty of apps run fine on it. If you go ahead, do it incrementally without stopping development. New features use the new architecture exclusively, older screens move across as you touch them for maintenance, and you avoid the dreaded rewrite freeze. Our month-long pause was a different animal, an emergency stabilization rather than a migration.

Do you still get memory leaks?

Rarely, but it happens. During major refactors the DevTools memory view stays open constantly so I can confirm objects get garbage collected after heavy screens are popped. It still needs watching.

What's the biggest mistake junior Flutter devs make?

Cramming business logic, network requests and error handling into one StatefulWidget, as though widgets were monolithic controllers instead of purely reactive visual elements. Separation of concerns matters more than anything else here.

Was the month worth it?

Yes. With the big structural changes in place, we went looking specifically for micro-optimizations, adding const constructors wherever possible, moving heavy JSON parsing into background isolates and cleaning up how assets were rendered. The app went from noticeably laggy to a silky smooth 60 frames per second.

When we presented the rewritten app, the stakeholders were blown away by how much more responsive it was. That was a massive win for the technical team. It also validated every difficult decision we'd had to make along the way.

Those late-night debugging sessions were incredibly stressful, and I needed every one of them to grow as an engineer. Flutter is just a tool. How you wield it decides your success or failure, and we learned that the costly way so you hopefully won't have to.

Refactoring is never really done. You keep refining and adapting as new architecture paradigms come along, and if your codebase terrifies you right now, take a deep breath and start breaking it apart methodically. Keep learning, question your assumptions, and when you're stuck, check the Flutter tag on Stack Overflow, because the community has usually solved your exact problem already. Then keep coding, stay curious and go build something awesome.

Suraj Bhandari

Written by Suraj Bhandari

Thanks for reading! If this article helped you, share it with someone who needs it.

Comments