Sat, Dec 24, 2022
Read in 2 minutes
In this post we take a look at "deferred" keyword with some example codes.
In Dart, deferred
is a keyword that is used in conjunction with code splitting to load libraries lazily at runtime.
Code splitting is a technique used to improve the startup time and memory usage of Dart applications. It allows you to split your application into smaller chunks, or “deferred libraries”, that can be loaded on demand as needed.
When you mark a library with the deferred
keyword, you are telling the Dart compiler to create a separate output file for that library. This output file is not loaded when the main application is loaded, but instead is loaded on demand when the library is first accessed.
Here is an example to illustrate the use of deferred
:
import 'dart:async';
import 'package:deferred_loading/deferred_library.dart' deferred as lazy;
void main() async {
print('Starting...');
await lazy.loadLibrary();
print('Library loaded.');
lazy.sayHello();
}
In this example, we have imported a library called deferred_library.dart
using the deferred
keyword. This means that the library is not loaded when the main application is loaded, but instead is loaded on demand when the library is first accessed.
We use the loadLibrary()
function provided by the deferred
library to load the deferred library. This function returns a Future
that completes when the library is loaded.
After the library is loaded, we can call its functions just like we would with a regular library. In this example, we call the sayHello()
function provided by the deferred_library.dart
library.
When we run this code, we will see the following output:
Starting...
Library loaded.
Hello!
In summary, the deferred
keyword in Dart is used in conjunction with code splitting to load libraries lazily at runtime. It allows you to split your application into smaller chunks that can be loaded on demand as needed. This can improve the startup time and memory usage of your Dart applications.