问题:

PWA安装到手机桌面之后,每次 Flutter Web 打包发布之后,第一次打开不能加载到最新的界面,关闭后,下一次打开才能加载最新的。

解决:

将下面代码添加到 web/index.html 中 。

const version = 1;

const checkAppUpdate = function() {
  caches.open('sugar-cache').then(function(cache) {
    // 检索版本号资源
    cache.match('/version').then(function(response) {
      if (response) {
        response.text().then(function(data) {
          var cachedVersion = parseInt(data, 1); // 将缓存的版本号转换为整数
          if (version > 1 && cachedVersion < version) {
            // 缓存的版本号较旧,需要更新
            window.showToast("There is a new version");
            window.location.reload();

            // 将最新版本添加到缓存
            var versionResponse = new Response(version.toString());
            cache.put('/version', versionResponse);
          }
        });
      } else {
        // 版本号资源不存在于缓存中,需要添加到缓存
        var versionResponse = new Response(version.toString());
        cache.put('/version', versionResponse);
      }
    });
  });
}

const swRegister = function() {
  const SW = navigator.serviceWorker
  if ('serviceWorker' in navigator) {
    // "/serviceworker.js"  './service-worker.js'   flutter_service_worker.js
    SW.register('./flutter_service_worker.js').then((registration) => {
        // 捕获到registration.installing触发
        registration.onupdatefound = function(){
          const installingWorker = registration.installing;
          installingWorker.onstatechange = function(){
            // 发布时每次更新了新的内容,用户首次看到的是旧的内容,要二次刷新的问题
            if(installingWorker.state === 'activated'){
              if(SW.controller){
                checkAppUpdate();
              }
            }
          }
        }
      },
      (err) => {
        console.log('ServiceWorker registration failed: ', err)
      }
    );
  }
}
swRegister();

参考:

https://blog.csdn.net/zmx_FZ/article/details/106206890

Service Worker 概览 :
https://developer.chrome.com/docs/workbox/service-worker-overview?hl=zh-cn

PWA介绍:
https://web.dev/learn/pwa/service-workers?hl=zh-cn