flutterdartflutter-provider

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?


Solution

  • TLDR; Choose the one you prefer, note that prefer_relative_imports is recommended in official Effective Dart guide

    First of all, as mentioned in this answer, Provider do not recommands package imports anymore.

    Dart linter provides a list of rules, including some predefined rulesets :

    Imports rules

    There is actually more than two opposites rules concerning imports :


    The two following are the one you mention :

    Which one should I choose?

    Choose the rule you want ! It will not cause any performance issue, and no rule would reduce errors over the other. Just pick one and make your imports consistent across all your project, thanks to Dart linter.

    I personnaly prefer using prefer_relative_imports, as it is recommended by Dart team, with this VSCode extension which automatically fix and sort my imports.