Flutter imports : relative path or package?

Augustin R picture Augustin R · Jan 11, 2020 · Viewed 9.2k times · Source

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?

Answer

Tarique Naseem picture Tarique Naseem · May 5, 2020

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.