This is a VS Code extension that sorts your dart / flutter imports with a single command.
There are three ways to activate the extension:
-
Using the shortcut:
ctrl+alt+o
-
Using the command palette:
- Open the command palette (Ctrl + Shift + P)
- Type and Run
Dart: Sort Imports
-
Save your active document (with
sortOnSave
set totrue
).
By default, this extension will group your dart imports according to source and package:<namespace>
.
You can set the extension to sort your dart imports whenever you save your
current active document. This is set to false
by default, but can be changed in the extension settings.
You can set your own sorting rules so that imports will be grouped and ordered according to your preference.
The sorting algorithm only looks at a certain part of the import statement, namely the parts between the quotes. Keep this in mind when writing your own rules.
For example, the following:
import 'package:something/path/to/import.dart' as something_else;
is simplified to
'package:something/path/to/import.dart'
See the following example:
// settings.json
{
"dartimportsorter.matchingRules": [
{
"label": "Flutter",
"regex": "^package:flutter.*$",
"order": 1,
"regexFlags": ["m"]
},
{
"label": "Dart",
"regex": "^dart:.*$",
"order": 2,
"regexFlags": ["m"]
},
{
"label": "Everything else",
"regex": ".*",
"order": 3,
"regexFlags": ["m"]
}
]
}
The extension comes with the following default rules:
[
{
"label": "Dart",
"regex": "^dart:.*$",
"order": 1,
"regexFlags": ["m"]
},
{
"label": "Flutter",
"regex": "^package:flutter/.*$",
"order": 10,
"regexFlags": ["m"]
},
{
"label": "Package imports that are NOT your app",
"regex": "^package:(?!<app_name>).*$",
"order": 100,
"regexFlags": ["m"]
},
{
"label": "Package imports that ARE your app",
"regex": "^package:<app_name>.*$",
"order": 101,
"regexFlags": ["m"]
},
{
"label": "Relative",
"regex": "^\\..*$",
"order": 1000,
"regexFlags": ["m"]
}
]
You project name is detected automatically from pubspec.yaml and replaces <app_name>
when the extension is used. You can use the <app_name>
placeholder in any custom rules you write.
If you don't provide custom rules in settings.json, then the extension will use these rules by default. If you provide any configuration whatsoever, then the extension will use only your configuration, completely disregarding the defaults.
{
"dartimportsorter.leaveEmptyLinesBetweenGroups": true
}
See Changelog
Contact me at aziznal.dev@gmail.com. I'd love to collaborate!
Configuration inspired by this extension (typescript import sorter)