DEV Community

Jordan Holland
Jordan Holland

Posted on • Originally published at developermemos.com

Excluding Dart files from static analysis

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:

include: package:flutter_lints/flutter.yaml

linter:
  rules:
    use_key_in_widget_constructors: false
Enter fullscreen mode Exit fullscreen mode

You just need to add a key for analyzer and add your exclusions below it with exclude, like this:

include: package:flutter_lints/flutter.yaml

analyzer:
  exclude:
    - 'lib/ui/something/file1.dart'
    - 'lib/data/something/file2.dart'  

linter:
  rules:
    use_key_in_widget_constructors: false
Enter fullscreen mode Exit fullscreen mode

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:

include: package:flutter_lints/flutter.yaml

analyzer:
  exclude:
    - 'lib/ui/something/file1.dart'
    - 'test/data/notifiers/**.mocks.dart'  

linter:
  rules:
    use_key_in_widget_constructors: false
Enter fullscreen mode Exit fullscreen mode

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:

include: package:flutter_lints/flutter.yaml

analyzer:
  exclude:
    - '**.g.dart'  
    - '**.mocks.dart'

linter:
  rules:
    use_key_in_widget_constructors: false
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)