Why is my IDE complaining at me?
Perhaps you’ve seen one of these warnings in your IDE:
Prefer relative imports for files in
DO avoid relative imports for files in
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:
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.
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:
In a subfolder:
In another subfolder of the parent folder: