package: imports, which utilize a logical namespace defined by the package configuration, relative imports resolve locations based on the directory hierarchy using standard URI path resolution rules.
Syntax and Path Resolution
Relative imports are defined using string literals containing a relative URI reference. The Dart compiler resolves these paths by merging the relative string with the URI of the current library.| Component | Description |
|---|---|
filename.dart | References a file located in the same directory as the current file. |
./ | Explicitly references the current directory. |
../ | Traverses to the parent directory. |
../../ | Traverses to the grandparent directory (recursive traversal). |
Directory Structure Example
The following project structure is used for the implementation examples:Implementation Examples
1. Importing a sibling file Inlib/utils/date_formatter.dart, importing a file in the same directory:
lib/main.dart, importing a file located deeper in the directory tree:
lib/models/user.dart, traversing up to the root of lib:
lib/models/user.dart, traversing up to lib and then down into utils:
Library Identity and URI Resolution
Dart identifies libraries uniquely by their resolved URI. A relative import inherits the URI scheme (e.g.,package: or file:) of the importing library.
If a file is imported via a package: URI in one context and a relative path that resolves to a file: URI in another, the Dart runtime treats them as two distinct libraries. This often occurs when importing lib files relatively from outside the lib directory (such as from test/ or bin/).
Example of Library Duplication:
- Context A:
main.dartimportsmodels/user.dart.- Resolved URI:
package:my_project/models/user.dart
- Resolved URI:
- Context B:
test/user_test.dartimports../lib/models/user.dart.- Resolved URI:
file:///path/to/my_project/lib/models/user.dart
- Resolved URI:
User object created in Context A is not compatible with the User type expected in Context B, resulting in type mismatch errors (e.g., “User is not of type User”). To maintain type consistency, imports should consistently resolve to the same URI scheme.
Master Dart with Deep Grasping Methodology!Learn More





