At Flutter live in December 2018 the Flutter team used a desktop app for their slide, they also give us a sneak peak of what has become Flutter web.

At google IO 2019 Flutter Web was open to everyone in a technical preview.

Today we will speak about Flutter application that work on Desktop, Mobile and Web with a single code base. To illustrate that we will use the well known counter example and add support for persistence of the counter for each supported platform.

The final code is in this repository all_platform_example

We need some sort of ‘plugins’ that work across all platform, for this example we will use 2 plugins that are located in the rc_cross repository.

The first plugin is rc_cross_platform who give us the platform we are running on !

The second plugin is rc_cross_preferences who allow use to save small data by using the best solution for the platform we are running on !

So if we are on mobile rc_cross_preferences will use the shared_preferences package, if we are on the web it will use the local storage, and on desktop it will write your key/value in a file.

Some screenshot of the application :

android :

linux:

This seems really cool but how it work ?

We will take the rc_cross_platform as an example.

If you look at the source code in lib/src you will see 4 files :

Let’s open platform_base.dart in this we define what we need across all platform it’s the base class for platform. We also have some code that are the same for each supported platform.

In platform_io.dart and platform_web.dart we have custom code for io (desktop / mobile) and web.

In platform_io.dart we use the Platform class from dart:io to back our value.

In platform_web.dart we set the web value of the PlatformBase to true (other are set to false by default).

Then we need a single file to import so it’s easy to use for the end user that file is platform.dart. We use conditional import to import the good file depending on where we are running. Here by default we import platform_io.dart but if we are in a js library, which happen when you compile your application with dart2js/ddc, it will replace that by platform_web.dart

We use the same technique in rc_cross_preferences the only change is that we use rc_cross_platform on the io side to choose between shared_preference/custom key/value file.

Manage State

We use Mobx as stated in the readme. It allow us to have a reactive way to be notified when the counter change. We have an extra Widget that load/save the counter. The rest is almost the same counter app from flutter create.

Sort of conclusion

WARNING: This is highly experimental and is subject to change drastically, as Flutter support more thing like Platform Channel for Desktop and Web.

It will be a really exciting time when all this will really come together.

There will be awesome opportunity to contributes to plugins to add support for these new platform.