Difference between import ‘../../file_name.dart VS import ‘package:Name/folder_name/file_name.dart
#dart
Answer
Overview
Dart supports two styles of import paths — relative (
text
../../file.darttext
package:myapp/path/file.dartRelative Import
dart// ../../file_name.dart // Path is relative to the CURRENT file's location import '../../utils/helpers.dart'; import '../models/user.dart'; import './widgets/custom_button.dart';
How it works:
textCurrent file: lib/features/auth/screens/login_screen.dart Import: ../../utils/helpers.dart Resolves to: lib/utils/helpers.dart
Package Import
dart// package:AppName/folder/file.dart // Path is always relative to lib/ folder import 'package:my_app/utils/helpers.dart'; import 'package:my_app/features/auth/models/user.dart'; import 'package:my_app/core/constants.dart';
How it works:
textApp name: my_app (from pubspec.yaml) Import: package:my_app/utils/helpers.dart Resolves to: lib/utils/helpers.dart (always from lib/)
Key Differences
| Feature | Relative text | Package text |
|---|---|---|
| Base path | Current file location | Always text |
| Portability | ❌ Breaks if file moves | ✅ Stable regardless of location |
| Readability | ❌ text | ✅ Clear full path |
| External use | Only within same folder | ✅ Works from outside lib/ (tests!) |
| Preferred | ❌ Generally avoid | ✅ Dart style guide recommends |
Same File, Two Styles
dart// Both import the SAME file: import '../../models/user.dart'; // Relative import 'package:my_app/models/user.dart'; // Package
When Relative Import Can Break
dart// If you move login_screen.dart to another folder: // OLD: lib/features/auth/screens/login_screen.dart // NEW: lib/screens/login_screen.dart // OLD relative import (now broken!): import '../../utils/helpers.dart'; // ❌ Wrong path now // Package import (still works!): import 'package:my_app/utils/helpers.dart'; // ✅ Unchanged
Linter Rule
yaml# analysis_options.yaml linter: rules: - always_use_package_imports # Enforce package: style # or - prefer_relative_imports # Enforce relative for same package
Recommendation: Use
imports throughout your project. They're consistent, portable, and work correctly from test files. The Dart style guide recommends package imports for your own code.textpackage: