Flutter 2.2 and Optimized Caching

·

2 min read

I've recently moved to Flutter 2.2 stable channel to take advantage of the new Flutter web caching optimization. This is a significant improvement to Flutter Web compared to earlier versions.

According to the Flutter blog, the behavior for web updates is improved in v2.2.

Flutter web updates

Flutter’s newest stable platform, web, has been improved in this release.

To start, we’ve optimized caching behavior with a new service worker-loading mechanism, and fixed double-downloading of main.dart.js. In previous versions of Flutter web, the service worker downloaded updates to your app in the background while giving your user access to the stale version of your app. Once that update was downloaded, the user wouldn’t see those changes until they refreshed the browser page a couple times. As of Flutter 2.2, when the new service worker detects a change, the user will wait until the updates are downloaded to use the app, but then they’ll see the updates without requiring a second manual refresh of the page.

Problem Overview

Changes to the web site were not reflected in the web browser as expected due to an old cache loading into browser.

This could be solved by forcing the server to send a no-cache header. However, this resulted in slow initial load times every time a person went to the web site.

Previous Workaround with Firebase Hosting Cache Control

I'm using Firebase Hosting for the web site. Previously, I used no-cache to make sure that people saw our newest updates to the web site. Due to slow initial load times this was not a satisfactory workaround. However, it was good-enough to use.

In my firebase.json file:

{
  "hosting": {
    "public": "build/web",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [{
      "source": "*",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "no-cache"
        }
      ]
    }]
  }
}

Although this works, it makes the site painfully slow to load every time.

Migration Status

  • switched to Flutter 2.2 in the stable channel. I was using Flutter 2.2 beta for testing
  • disabled no-cache in http header on Firebase hosting

Current firebase.json

{
  "hosting": {
    "public": "build/web",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

Migration Results

Site loads much faster and the changes to the site are reflected with normal reloads or opening up a new tab. This is a great update.

To Do

  • switch to Dart 2.13. Currently on Dart 2.11 without sound null-safety
  • upgrade firebase_core_web
  • fix problems with code