Relative vs package imports in Flutter and Dart

Suragch
5 min readJan 6, 2022

Why is my IDE complaining at me?

Perhaps you’ve seen one of these warnings in your IDE:

Prefer relative imports for files in lib/.

DO avoid relative imports for files in lib/.

Messages like these come from Dart’s linting rules, which are warnings generated by dart analyze and communicated to you by your IDE. There is a whole list of linting rules and some of them even conflict with each other.

Relative to the topic of this article, there are a few different linting rules that relate to imports:

1. prefer_relative_imports
2. avoid_relative_lib_imports
3. always_use_package_imports

The first and the third are mutually exclusive. The fact that they conflict means you have to make a choice. You can’t use all of them.

You probably came to this page because you’re using a set of lints that someone else chose, whether that’s Effective Dart, or Flutter Lints, or Very Good Analysis, or something else, and you’re not following their rules. (Read Flutter Linting Comparison for more about this.)

As a responsible developer, the solution is to understand the problem and then to make your own decision rather than blindly following someone else. It’s OK to follow someone else, just not blindly.

Defining the terms

First, it’s important that you know the difference between relative and package imports.

Relative imports

A relative import refers to getting another file within the lib folder of your own project without referencing the name of the project itself. A relative import is only used to import your own files in your own project. You never use relative imports to reach into other packages. Here are a few examples of relative imports:

In the same folder:

import 'book.dart';

In a subfolder:

import 'core/book.dart';

In another subfolder of the parent folder:

import '../core/book.dart';

Package imports

Suragch

Flutter and Dart developer. Twitter: @suragch1