Reduce your flutter web app loading time

Schaban Bochi
3 min readFeb 13, 2022

--

Do you know this problem, when you are working on a web app with flutter and after weeks of working you are ready to release your app, You deploy it, you open the app in your browser to enjoy the wonderful work you have done. But the app takes too long to start!!
What's wrong?! You go to the network tab and see that main.dart.js is 2.9 MB!!! ☠️☠️

Great 😑. What to do now? How to reduce the size of this file? That was my question for the last two weeks.
After a lot of searching, I did not find a way to solve this, and there is an open issue about this. The useful thing I could find is Lazily loading which could split your code in multiple JavaScript files, read more about it.

So I tried to use this with qlevar_router a package that simplify navigator 2 that i use, read more about it. And that is the result

I was able to reduce the file size from 1.6 MB to 471 KB in an easy, simple way 🥳.

That whole idea was to split the files according to the pages in the apps. So the file of this page will be loaded right before navigating to this page. And the files of the pages that user did not visit will not load at all 🤗.

To test this, I have created a test project, you can find it on GitHub.
The project contains three pages:
- Main Page: Simple page to navigate to the other pages.
- Users Page: a page that contains a lot of test data.
- Categories Page: a page that use a package (simple_animations)

With qlevar_router you can define the routes for these pages as following.

Routes definition for qlevar_router

And with the Middleware feature from qlevar_router, I defined a middleware that loads the file for the page before opening it using lazy laoding.

Deferred loader middleware

And used it in my routes and imported every page as deferred

and then I have build my app to see that flutter, have made a file for every page 😎. And the result was

To compare the results, I have built the project with HTML and canvas kit render in the normal and deferred way and that was the results. You can find them here too Results.

As shown in the result, flutter built a JavaScript file for every page we have.
- main.dart.js :Contains the basic info to run the app and only the main_page.dart, that is why I recommend keeping the first page in your app as small and simple as possible, like a Splash screen and as the splash screen is shown load the file for your next page to show.
-main.dart.js_1.part.js: contains the information for the users_page.dart, if you open the JS file you will find the test Users data in it.
- main.dart.js_2.part.js: contains the information for the categories_page.dart and the extra package (simple_animations) in it. Which mean that the packages too will only be loaded when needed.

I hope this method could solve this problem for you or gives an idea on how to do it.
Happy coding.

--

--