— Dart, Flutter, Static Analysis, Flutter Tips — 1 min read
I wrote a couple of posts about linting this year, but this one is about excluding files from static analysis. After adding static analysis to most of my Flutter projects I found that sometimes there were files that I didn't want to be warned about.
A good example of this is if you use something like mockito
or json_serializable
. When you implement these kinds of packages in your project you run build_runner
and they generate code for you. Sometimes the analyzer will pick up issues with the generated code. You're not going to edit generated code to squash linting issues(or you shouldn't edit it anyway).
I got sick of the generated code files in my project showing up in the 'Problems' tab of VSCode so I finally decided to go digging for a solution this week and it was refreshingly straight forward. You just need to make some small changes to your analysis_options.yaml file. So for example if your file looks something like this:
1include: package:flutter_lints/flutter.yaml2
3linter:4 rules:5 use_key_in_widget_constructors: false
You just need to add a key for analyzer
and add your exclusions below it with exclude
, like this:
1include: package:flutter_lints/flutter.yaml2
3analyzer:4 exclude:5 - "lib/ui/something/file1.dart"6 - "lib/data/something/file2.dart"7
8linter:9 rules:10 use_key_in_widget_constructors: false
You can also use '**' to target specific file patterns, so if you wanted to ignore all the .mocks.dart
files in a specific test directory you could do something like this:
1include: package:flutter_lints/flutter.yaml2
3analyzer:4 exclude:5 - "lib/ui/something/file1.dart"6 - "test/data/notifiers/**.mocks.dart"7
8linter:9 rules:10 use_key_in_widget_constructors: false
You can also target all files with a specific pattern globally too. In my project I wanted to exclude all files with .mocks.dart
and .g.dart
so I ended up with these settings:
1include: package:flutter_lints/flutter.yaml2
3analyzer:4 exclude:5 - "**.g.dart"6 - "**.mocks.dart"7
8linter:9 rules:10 use_key_in_widget_constructors: false
The above examples worked for me in a Flutter project with sdk: ">=2.12.0 <3.0.0"
, and you can find more discussion about the topic here. It looks like the are some reports recently about issues with Dart 2.13.0 though 😅. And speaking of linting, if you want to hear my (very brief) thoughts about flutter_lints then check out my post from the other week.