Change VS Code to auto-import files in flutter relatively
Asked Answered
S

3

11

So, here is the problem:

Whenever I am coding with Flutter and Dart, and I use a feature from another file, when I press Tab, VS Code will auto-import the file for me.

The thing is, VS Code will use the package import syntax, like import 'package:<project_name>/<file_path>';. But I prefer relative import syntax.

So, is there a setting I can change in VS Code for Dart to configure it to use relative imports by default?

Thanks!

Soul answered 29/1, 2022 at 2:54 Comment(1)
Does this answer your question? Flutter imports : relative path or package?Kunlun
L
5

It isn't necessary to download an extension. As explained here, simply add this to the analysis_options.yaml file:

linter:
  rules:
    - prefer_relative_imports
Laticialaticiferous answered 11/10, 2023 at 5:5 Comment(0)
K
9

While importing, you can find both option by tapping on yellow bulb or pressing ctrl+.

enter image description here

Another handy thing, using dart-import extension on Vs-code.

Kunlun answered 29/1, 2022 at 3:55 Comment(3)
Thanks, this works great. Is there a way to have the relative path have the ./ at the beginning?Soul
i could not find that way,Kunlun
ok thanks @Yeasin Sheikh!Soul
S
5

Personally, I am using dart-import extension. There is an extension setting you can turn on to modify imports on save. So, you can have a consistent import structure without needing to choose every single time.

dart import fix on save

There is a recommendation in effective dart guideline for relative path import usage.

Subsistent answered 6/8, 2022 at 7:38 Comment(1)
Note: After installing the extension, I had to restart VS Code before the "Fix On Save" option appeared.Choanocyte
L
5

It isn't necessary to download an extension. As explained here, simply add this to the analysis_options.yaml file:

linter:
  rules:
    - prefer_relative_imports
Laticialaticiferous answered 11/10, 2023 at 5:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.