Compiling Flutter Web apps in a better way

Use case

Make so that when I compile my Flutter website that each page/route is compiled in its own and different .js file instead of the entire code all in 1 single .js file and having the user download the entire website. I am aware that I can use deferred loading to load imports only when they are actually needed, but that’s different than loading pages. I am also aware the this is helpful to provide the PWA functionality but it shouldn’t take a long time for the user to see the actual website content while Flutter starts up and starts loading all its resources which takes quite some time every time I visit a Flutter website.


Compile each page that is provided in the routes property for the MaterialApp in main.dart to its separate .js file and when the user goes to a specific route, the resources for that route are loaded. It would also be useful if package/imports are loaded only when they are actually being used instead of loading the entire library regardless if it is being actually used, example:
I have a function that I call when a user clicks on a button:

import 'some_library.dart' as some_library;

Future<void> trigger() async {
  // Makes use of the `some_library` import. This import is only being used in this function.

And then I have this button:

  text: 'Button',
  onPressed: trigger,

Now that trigger function is the only place that is using the some_library import. If the user doesn’t click on the button, the library should never be loaded. Once there is a place where it calls to use the some_library then it should actually load the library.

It would be great for Flutter web to expand and go beyond serving single-page web apps.

1 thought on “Compiling Flutter Web apps in a better way

  1. Doing something like this out-of-the-box would mean the tooling would need to be aware of a particular screen/route structure in the app. However, in practice our users can roll all kinds of screen structures, and not even use Flutter’s built-in router. So we will continue relying on deferred imports for this use-case.

    However, if you can somehow serialize the structure of routes from your app (e.g. using annotations), you could build your own code generator that generates deferred imports automatically. Something like this would be out of scope for Flutter to support though.

Comments are closed.