How to transform Flutter web app into a PWA?

Viewed 2247

I am making a new Web application with Flutter web. I want to add service workers to my app in order to make it a PWA.

What I need to use to achieve my goal ?

I have tried to do it with dart packages (service_worker or pwa), but they are deprecated for Dart 2.

2 Answers

Since a service worker is just javascript code you can write one in plain javascript (e.g. in a sw.js file), bundle it with your flutter web app and then register the service worker from the index.html file like this (source):

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js');
}

You currently need to switch to Flutter Channel Dev (at Feb 17th 2020, current Dev version 1.15.3)

For existing projects, use the terminal to hit the command:

flutter create .

For new projects, you would have a 2 files: manifest.json and index.html inside your web folder.

While checking index.html you would notice the following script:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function () {
     navigator.serviceWorker.register('/flutter_service_worker.js');
  });
}

If the script is not there, added inside <body></body>

This script creates the PWA support for you and be able to "install" the app on a device (this also includes MacOS)

Follow this GUIDE to complete your PWA functionalities.

Related