Skip to main content

Making a Dart web app offline-capable: 3 lines of code

Another article about Dart from Istvan Soos is about Progressive Web Apps, published today. — Filip Hracek

Have you ever tried to load a web application (maybe a game or a measurement converter) and couldn’t use it because the network was down? That’s an awful experience, but luckily we have the technology to make such apps available for our users.

For most apps and games, this can be done with 3 lines of Dart code and 1 command in the terminal. In this short article I’ll guide you through the steps, and make sure that you can always play Pop, Pop, Win!

Pop, Pop, Win! (code) — a Minesweeper implementation in Dart.

Service workers

A service worker is a JavaScript file that runs in the background. It can control the web page or the site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion.

It is a non-intrusive web technology: service workers can improve the user experience if the browser supports them, but the site can operate just fine in their absence (with the default web behavior). This is a useful property that enables progressive web applications (PWA), where you can provide more advanced features to the majority of the users, while making sure that the rest aren’t locked out.

As a background processing thread, a service worker can help with:
  • offline mode (fetching resources from cache while the network is down)
  • caching strategies (for near-instant cached responses that can be updated later with fresh content)
  • push notifications (like in a mobile app)
  • messaging (if the application is open on multiple tabs)
The important feature for our offline gaming experience is this: we would like to play Pop, Pop, Win!, and not meet this dinosaur:

Fun fact: you can play with that dinosaur by pushing the up arrow key.

Progressive web app with Dart

Supporting offline mode requires roughly the following:
  1. Determining which resources to put in the cache for offline use.
  2. Creating a service worker that prepares a cache of these resources.
  3. Registering the service worker, so that subsequent requests can be served from the offline cache (in case the network is down).
  4. In that service worker, pre-populating the offline cache with the URLs, and also handling the appropriate fetch request either from the cache, or from the network.
  5. Making sure that the service worker detects changes to the app or static assets, and puts the new version in the cache.
While the above list may sound a bit scary, we have a pwa package in Dart that does most of the work for us, providing a high-level API and automating most of the work.

Changes in your application

Import the pwa package in your pubspec.yaml:
  pwa: ^0.1.2
After running pub get, add the client to your web/main.dart:
import ‘package:pwa/client.dart’ as pwa;
main() {
  // register PWA ServiceWorker for offline caching.
  new pwa.Client();
The above code handles item 3 from the above list by registering the service worker (which we will create in the following step). Right now we don’t use the Client instance for anything else, but as the pwa package gets new features, it may become useful for other purposes.

Automatically generated progressive web application

The pwa package provides code generation that handles items 1–2 and 4–5 from the above list. To ensure proper cache use (both populating and invalidating the cache) use the following workflow:
  1. Build your web app with all of the static resources landing in build/web: pub build
  2. Run pwa’s code generator to scan (or rescan) your offline assets: pub run pwa
  3. Build your project again, because you need to have your (new) pwa.dart file compiled: pub build
These steps produce a file named lib/pwa/offline_urls.g.dart that contains a list of the offline URLs to be cached. The .g.dart extension indicates that the file is generated and may be overwritten automatically by pwa’s code generator tool.

On the first run, this workflow generates the web/pwa.dart file that contains your service worker with reasonable defaults. You can modify this file (to customize the offline URLs or use the high-level APIs, for example) because the code generator won’t change or override it again.


While Dartium is great for most web development, at the moment it’s hard to use with service workers. We recommend using Chrome or Firefox instead.

Cache invalidation is one of the hardest problems in computer science. The underlying Web Cache API provides some guarantees, and the pwa library goes to a great length to gracefully handle the edge cases, but don’t treat the cache as reliable storage for anything really important. Make use of the cache when it is available, and fail gracefully when it’s not.


You can now deploy the new version of your application. Or try the offline Pop, Pop, Win! game.

After opening the game and playing one round, shut down your wi-fi or unplug the network cable, and then reload (or retype the URL). If you’re using Chrome or Firefox, your game should be up and running. Good luck, have fun!

— István Soós, March 28, 2017, canonical link


Popular posts from this blog

Const, Static, Final, Oh my!

Posted by Seth Ladd

(This is an "oldie but a goodie" post originally written by Bob Nystrom. It is being posted here as the explanations still ring true.)

Bob writes:

"static", "final", and "const" mean entirely distinct things in Dart:

"static" means a member is available on the class itself instead of on instances of the class. That's all it means, and it isn't used for anything else. static modifies *members*.

"final" means single-assignment: a final variable or field *must* have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies *variables*.

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies *values*. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determ…

The new AdWords UI uses Dart — we asked why

Google just announced a re-designed AdWords experience. In case you’re not familiar with AdWords: businesses use it to advertise on and partner websites. Advertising makes up majority of Google’s revenue, so when Google decides to completely redo the customer-facing front end to it, it’s a big deal. The Dart team is proud to say that this new front end is built with Dart and Angular 2. Whenever you asked us whether Google is ‘even using Dart for anything,’ this is what we had in mind but couldn’t say aloud. Until now. We asked Joshy Joseph, the primary technical lead on the project, some questions. Joshy is focusing on things like infrastructure, application latency and development velocity, so he’s the right person to ask about Dart.Q: What exactly did we launch on Monday?It’s a complete redesign of the AdWords customer experience that is rolling out slowly as a test to a small initial set of advertisers. The most noticeable thing is probably the Material Design look and f…

Dart 1.12 Released, with Null-Aware Operators and more

Dart 1.12.0 is now released! It contains the new null-aware operators language feature, and enhancements to pub, Observatory, dartdoc, and much more.

Null-aware operators

The new null-aware operators help you reduce the amount of code required to work with references that are potentially null. This feature is a collection of syntactic sugar for traversing (potentially null) object calls, conditionally setting a variable, and evaluating two (potentially null) expressions.

Click or tap the red Run button below to see them in action.


  if null operator. `expr1 ?? expr2` evaluates to `expr1` if not `null`, otherwise `expr2`.


  null-aware assignment. `v ??= expr` causes `v` to be assigned `expr` only if `v` is `null`.


  null-aware access. `x?.p` evaluates to `x.p` if `x` is not `null`, otherwise evaluates to `null`.


  null-aware method invocation. `x?.m()` invokes `m` only if `x` is not `null`.

Learn more about Dart's null-aware operators in our Language Tour.

.packages fi…