← Back to posts Cover image for Optimizing Flutter Web (WASM) Cold Start: A Case Study in Speeding Up PWAs

Optimizing Flutter Web (WASM) Cold Start: A Case Study in Speeding Up PWAs

· 5 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

The Silent Killer of Flutter Web PWAs: Taming the Cold Start

You’ve built a beautiful, offline-first Flutter Web PWA using the --wasm flag for that sweet, near-native performance. You deploy it, full of optimism. Then you check your analytics. The bounce rate on mobile is staggering. Users on slower 4G connections are abandoning the app within seconds. The culprit? A brutal cold start time of 20 seconds or more. The user’s first impression is a loading spinner, and by the time your app is ready, they’re long gone.

This isn’t a hypothetical. It’s a common reality when shipping Flutter Web applications, especially with WebAssembly (WASM). The initial payload can be hefty, and without optimization, network speed becomes the single biggest bottleneck to user adoption. Let’s break down how to diagnose and surgically fix this problem, transforming a 20-second start into a snappy 3-4 second experience.

Diagnosing the Problem: What’s in the Bundle?

First, you need to see what the user is actually downloading. Build your app for release and inspect the output.

flutter build web --release --wasm

Navigate to your build/web directory. The key files to look at are main.dart.js, the large WASM module (flutter.js may load a .wasm file), and any other large assets. Use a tool like source-map-explorer or simply check the network panel in your browser’s developer tools (using the “Slow 3G” throttling preset) to see the download waterfall.

You’ll likely find three main offenders:

  1. The Flutter Engine & Framework (WASM/JS): This is somewhat fixed, but its impact can be mitigated.
  2. Fonts: Custom fonts can be multi-megabyte bloat if not subset.
  3. Third-Party Library Initialization: Some libraries, like Firebase, can perform blocking network requests on startup.

Optimization 1: Slashing Font Bloat with Subsetting

A single .ttf or .otf file for a font family contains thousands of glyphs you’ll never use (special characters, multiple language sets). Flutter’s default font loading can be naive. The solution is font subsetting.

Don’t just drop the full font file in your pubspec.yaml. Instead, use the google_fonts package in a specific way, or pre-process your fonts.

For Google Fonts, ensure you are not dynamically downloading the font on the web. Pre-bundle a subset:

# pubspec.yaml
flutter:
  fonts:
    - family: Inter
      fonts:
        - asset: assets/fonts/Inter-Subset.woff2

Generate the subset file using a tool like pyftsubset (from the fonttools Python package):

pyftsubset MyFont.ttf --output-file=Inter-Subset.woff2 --flavor=woff2 --text="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?/`~"

The key takeaway: Never ship a full .ttf file to the web. Always subset.

Optimization 2: Deferring Firebase and Heavy Libraries

Many apps use Firebase. On web, the default initialization of Firestore or Realtime Database can make network calls that block the main thread. The fix is lazy loading.

Instead of initializing Firebase and setting up listeners immediately at main(), delay them until after the core app is interactive.

Before (Problematic):

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: myOptions);
  // This might trigger early channel setup
  runApp(const MyApp());
}

After (Optimized):

void main() {
  runApp(const MyApp());
}

// Within your first meaningful widget (e.g., HomePage), initialize lazily
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<void>? _firebaseInitialization;

  @override
  void initState() {
    super.initState();
    // Defer the initialization until after build
    _firebaseInitialization = _initializeFirebase();
  }

  Future<void> _initializeFirebase() async {
    await Firebase.initializeApp(options: myOptions);
    // Now it's safe to set up streams or listeners
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _firebaseInitialization,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        // Your main app UI here, Firebase is ready
        return const MyAppContent();
      },
    );
  }
}

This ensures the user sees your app’s UI framework immediately, while non-essential services load in the background.

Optimization 3: Enforcing Brotli Compression on Your Server

This is a server configuration step, but it’s critical. Gzip (Content-Encoding: gzip) is good, but Brotli (Content-Encoding: br) is significantly better for text-based assets like JavaScript, WASM, and CSS.

A typical Flutter WASM main.dart.js might be:

  • Uncompressed: ~15 MB
  • Gzipped: ~6 MB
  • Brotli-ed: ~3.5 MB

That’s a ~40% further reduction from Gzip! Most modern browsers support Brotli. You must configure your web server (NGINX, Apache, Cloudflare, Firebase Hosting, etc.) to serve .js, .wasm, .json, .css files with Brotli compression. For Firebase Hosting, it’s enabled by default. For others, a quick search for “enable Brotli [your server]” will yield instructions.

Putting It All Together

The dramatic reduction from 20+ seconds to 3-4 seconds isn’t magic; it’s the compound effect of these three optimizations:

  1. Font Subsetting cuts 1-5 MB from your payload.
  2. Deferred Firebase Init gets your UI interactive before network-dependent libraries are ready.
  3. Brotli Compression can halve the size of your core application bundle.

The process is simple: Profile, Identify, and Attack the largest bottlenecks. Always measure with network throttling enabled. Your users on slower connections aren’t an edge case—they’re often the majority, and their first impression will determine your app’s success.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.