18

I'm using Android Studio for the development of Flutter. I want the auto-imported statements to be imported as in a relative path to the file instead of as an absolute path from the root. I want this thing only for the custom Widgets I'm creating, not for Flutter/Dart internal packages.

Actual

import 'package:stack_app/modules/home/widgets/header.dart';

Expected

import 'widgets/header.dart';

I have seen the setting in Andriod studio, but couldn't find it to customize. Can anyone direct me to some of this IDE plugin/settings where I can change such settings?

Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
  • Have you tried using VSCode? In this [answer](https://stackoverflow.com/a/66188522/9455325) you can install the [dart-import plugin](https://github.com/luanpotter/vscode-dart-import). You can just add a keybinding to the "Fix Imports" command. – rickimaru Mar 22 '21 at 10:10
  • 2
    @rickimaru I don't use VSCode, I prefer Android Studio – Yashwardhan Pauranik Mar 23 '21 at 10:40

3 Answers3

2

There is a workaround for this: Firstly auto import it with absolute path. Then, use the "Convert to a relative import" to make it a relative import.

Example:

enter image description here

Result:

enter image description here

By the way, why do you want to have relative imports? This may be a X-Y problem. For example, by using absolute imports, it is clear where a file is used, by simply search strings like import 'package:sth/your_file.dart'.

ch271828n
  • 15,854
  • 5
  • 53
  • 88
  • 4
    According to dart guide to prefer using relative imports for project files. – Ariel Magbanua Mar 27 '21 at 15:54
  • and by the way, if you import relatively when you have a problem with the project and have to change the project folder or something like that if have your folder struct the same just with different names then you don't have to change all package name again – reza47 Sep 09 '21 at 14:40
  • 1
    Relative imports are short. – Seonghyeon Cho Nov 16 '21 at 06:50
1

I also prefer to use relative imports and I usually use the "convert to relative import" function in android studio. Now I have started to see that that option doesn't exist sometimes.

Meconer
  • 11
  • 2
  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30593730) – Robert Dec 15 '21 at 19:19
0

You can set linter rules in analysis_options.yaml

#analysis_options.yaml
linter:
    rules:
        prefer_relative_imports: true
Srinadh
  • 386
  • 4
  • 11