Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter imports : relative path or package?

In Flutter, for importing libraries within our own package's lib directory, should we use relative imports

import 'foo.dart' 

or package import?

import 'package:my_app/lib/src/foo.dart' 

Dart guidelines advocate to use relative imports :

PREFER relative paths when importing libraries within your own package’s lib directory.

whereas Provider package says to always use packages imports :

  • Always use package imports. Ex: import 'package:my_app/my_code.dart';

Is there a difference other than conciseness? Why would packages imports would reduce errors over relative imports?

like image 809
Augustin R Avatar asked Jan 11 '20 09:01

Augustin R


People also ask

How do I fix imports in flutter?

Run the command "Fix Imports" from the Command Palette; all imports from your own package will become relative. Also, the "Organize Import" command will be called. The only command added (so far) is "dart-import. fix"; you can bind it as desired.

What is export in Dart?

When you create a new library and use other libraries you want to make available automatically when using your package, then you use export : library mylib; export 'otherlib.dart'; // Definitions. You can use the show keyword to import/export only some parts of a library (like a class or something).


1 Answers

From the same Dart guidelines, further down they give this reason for the relative imports:

There is no profound reason to prefer the former—it’s just shorter, and we want to be consistent.

Personally, I prefer the absolute method, despite it being more verbose, as it means when I'm importing from different dart files (in other folders), I don't have to work out where the file to be imported is, relative to the current file. Made-up example:

I have two dart files, at different folder levels, that need to import themes/style.dart:

One is widgets/animation/box_anim.dart, where the relative path import would be:

import '../../themes/style.dart'; 

The other is screens/home_screen.dart with the relative import:

import '../themes/style.dart'; 

This can get confusing, so I find it better to just use the absolute in both files, keeping it consistent:

import 'package:myapp/themes/style.dart'; 

And just stick that rule throughout. So, basically, whatever method you use - Consistency is key!

The Linter for Dart package, also has something to say about this, but is more about the Don'ts of mixing in the '/lib' folder:

DO avoid relative imports for files in lib/.

When mixing relative and absolute imports it's possible to create confusion where the same member gets imported in two different ways. An easy way to avoid that is to ensure you have no relative imports that include lib/ in their paths.

like image 102
Tarique Naseem Avatar answered Sep 20 '22 16:09

Tarique Naseem