How I Halved Our Flutter App Startup Time After Trying Everything
Introduction
Last month our Crashlytics dashboard filled up with red, and it was the bad kind: a bug we couldn't reproduce was crashing the app for our most active users. I'm the lead developer, so it was my problem to fix.
Flutter makes it so easy to get pixels on the screen that you can forget you still have to deal with memory, async timing, and real devices. Our app had grown big and messy over time, and now that was costing us.
The next few weeks were mostly coffee, refactoring, and some days where nothing seemed to work. By the end, we had changed how we build mobile apps. This post covers what went wrong and what we changed.
The Immediate Crisis
Flutter wasn't the problem. The way we were using it was. Our screens mixed big initialization blocks, API calls, and data parsing right into the layout code. A small UI change from the product team would somehow break a network request on a different screen. Nobody fully understood the codebase anymore.
I spent hours adding print statements to lifecycle methods. When I ran the app, the terminal filled up with disposal errors and null exceptions. We were passing BuildContext into async calls and using it after the await without checking whether the widget was still mounted. It was only a matter of time before that blew up in production.
Thinking About Architecture
Nobody on our team was a weak Flutter developer. The animations were smooth, the algorithms were fine, and the app still came apart once real traffic hit it, because our screens were holding API calls and parsing code that had no business sitting in a build method.
Good architecture means planning for the bad cases from the start. Assume the network will drop halfway through a request. Assume users will tap the same button five times in a row. Assume the OS will kill your background work when you least expect it. Write your code with all of that in mind.
To make this stick, we tightened up code review. If a pull request puts network calls directly inside a widget, it gets sent back. People grumbled about that for a while, since features took longer to get merged, and then went quiet once fixing a bug stopped meaning a hunt through every screen that touched the same API.
If I had to keep one rule from all this, it'd be keeping API calls and data parsing out of widgets. When a request breaks now, I open the notifier that owns it, which beats scrolling through a build method trying to work out where the call even happens. Once this becomes a habit, building and maintaining a large Flutter app gets a lot less painful. It can even be fun.
Here's the kind of code we were dealing with:
// The way we used to handle things
Future<void> performAction(BuildContext context) async {
try {
showLoading(context);
final result = await apiService.fetchData();
Navigator.pop(context); // Crashes if the screen was already popped.
Provider.of<StateStore>(context, listen: false).update(result);
} catch (e) {
print('Error: $e');
}
}
This one function was behind hundreds of crashes we couldn't explain at first. You shouldn't use a context after an await without checking context.mounted, and adding that check everywhere is only a patch. The real fix was to move this logic out of the widget entirely.
// How we handle it 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); // The UI just reacts to state
} catch (e, st) {
state = AsyncError(e, st);
}
}
}
The Turning Point
Once we admitted how much technical debt we had, we spent the next several sprints refactoring. We separated the presentation layer from the business logic. It was slow, tedious work, but it paid off.
Our Crashlytics error rate dropped by more than 80%. The app felt faster, even on older, cheaper Android phones. The team was happier too, because they could finally trust the codebase again.
Frequently Asked Questions (FAQ)
How do you pass data between screens that aren't connected?If the data needs to change, I don't pass it through navigation arguments. I keep it in a state manager or a shared repository so there's one source of truth, and both screens listen to it.
How do you deal with huge widget classes?I break them up. If a build method goes past about 50 lines, I pull parts of it out into their own stateless widgets. It's easier to read, and smaller widgets mean Flutter rebuilds less when something changes.
Is it worth moving a large app from Provider to Riverpod or Bloc?Yes, but do it gradually and don't stop feature work to do it. Use the new approach for new features, then move older screens over when you're already working on them. That way you avoid a long "rewrite freeze."
Do you still get memory leaks?Sometimes, but rarely. During big refactors I keep the DevTools memory profiler open and check that heavy screens are actually garbage collected after they're popped. You still have to keep an eye on it.
Final Thoughts
Those late-night debugging sessions were stressful, but I learned more from them than from almost anything else in my career. Flutter is just a tool. Whether your app holds up depends on how you use it. Hopefully what we went through saves you some of the same pain.
Refactoring is never really done. You keep adjusting as your app grows and as better patterns come along. If your codebase scares you right now, start small and pull it apart one piece at a time.
Keep learning, question your assumptions, and when you get stuck, check Stack Overflow's Flutter tag. There's a good chance someone has already hit your exact problem and solved it. Good luck, and go build something good.
Comments
Post a Comment