Syntax
To declare a deferred import, use thedeferred as keywords followed by a namespace identifier.
Mechanism
The deferred import process involves three distinct technical stages:- Declaration: The
deferred asclause creates a placeholder namespace for the library. At this stage, the symbols within the library are not available for execution. - Invocation: The Dart compiler implicitly injects a method named
loadLibrary()into the namespace of the deferred import. This method returns aFuture<void>. - Resolution: When
loadLibrary()is called, the runtime fetches the code (if not already loaded) and resolves the symbols. Once theFuturecompletes, members of the library are accessible via the namespace prefix.
Implementation Example
The following example demonstrates the required pattern: importing with a prefix, awaiting the load future, and accessing members through the prefix.Technical Constraints
- Mandatory Prefix: Deferred imports must specify a prefix using
as. - Asynchronous Access: The
loadLibrary()method is always asynchronous. Even if the library has already been loaded by a previous call, the method returns aFuturethat completes immediately. - Constant Evaluation: Constants defined in a deferred library cannot be used as compile-time constants in the importing file because the values are not available at compile time.
- Type Usage: Types from a deferred library can be used in type annotations (e.g.,
utils.MyClass myVar;). However, they cannot be used in theextends,with, orimplementsclauses of a class declaration, as the class hierarchy must be resolved at startup. - Instantiation: While type annotations are permitted, you cannot construct an instance of a class from a deferred library until
loadLibrary()has completed. - Multiple Imports: If the same library is imported deferred in multiple places or both deferred and non-deferred, the runtime ensures the code is loaded only once.
Master Dart with Deep Grasping Methodology!Learn More





