how to lazy import packages in flutter

Viewed 1354

I have a flutter web app , And i don't want to deliver some of widgets (views) to all users

my web app content 4 views it should appear and ship to all users , And my app also contain a 20 - 25 views or routes for the admin dashboard

is any way to lazy load this widgets on demands in the runtime ? to avoid ship all pages to all users

1 Answers

i found the solution , there is suffix keyword you need to add after the import statement deferred loading.

example:

import 'package:my_web_app/views/About.dart';

its become:

import 'package:my_web_app/views/About.dart' deferred as about;

then you need to call:

await about.loadLibrary() whenever you need to load the package, at this moment our package is only initialized but we don't inject it in the elements tree, and to call our class or widget from from loader we should use Widget myLazyWidget = about.About() , the about is the loader and the About() is the the widget (in my case) , now i can use it normal and add it into widget tree.

you can read more on : https://dart.dev/guides/language/language-tour#lazily-loading-a-library

Related