Search code examples
flutterlintcicdflutter-lints

How to suppress depend_on_referenced_packages just for a specific import, not the whole file?


After upgrading to Flutter 3.0 I started to get a lot of depend_on_referenced_packages lint issues when running flutter analyze. If I remove the reported imports the compilation breaks. Most of the issues are with package:collection/collection.dart which provides extension methods.

Currently the best I could find is to suppress this lint for the affected files by adding // ignore_for_file: depend_on_referenced_packages. However I like this lint (and in general I'd want to keep as much lints enabled as possible), so is there a way to suppress the lint only for a just a specific import and not for all imports in the file?

Relevant sections of pubspec.yaml:

...
environment:
  sdk: ">=2.17.1 <3.0.0"
  flutter: ">=3.0.1"

...
dev_dependencies:
  flutter_lints: ^2.0.1

Running:

$ flutter analyze
...
   info • Depend on referenced packages • lib/preferences/palette_spec.dart:3:8 • depend_on_referenced_packages
   info • Depend on referenced packages • lib/ui/parts/circular_menu.dart:5:8 • depend_on_referenced_packages
...

Source code examples:

database_utils.dart (firstWhereOrNull is from collection.dart):

...
import 'package:collection/collection.dart';
...
  Activity? _getActivityById(int id) {
    return activities.firstWhereOrNull((element) => element.id == id);
  }
...
  Record? _getRecordById(int id) {
    return records.firstWhereOrNull((element) => element.id == id);
  }

palette_spec.dart (forEachIndexed is from collection.dart):

...
import 'package:collection/collection.dart';
...
          paletteStr.split(",").forEachIndexed((index, colorStr) {
...
          });

circular_menu.dart:

...
import 'package:vector_math/vector_math.dart' as vector;
...
    final angle = vector.radians(90.0 / (widget.children.length - 1) * index + angleFix);

Note: the root cause is that collection is brought in as a transitive dependency.

Originally I misunderstood the lint. Explanation to Petr's solution: when he says "lint is reported if you depend on a transitive dependency" it means that somewhere in my code I have an import which imports stuff from that dependency. But at the time of the lint that dependency is only transitive, not direct. Therefore if I'd decide - for whatever reason - to not depend on the package which brings that in then suddenly I'd have an error out o the blue for that import. The lint tries to make that dependency graph more direct.


Solution

  • This lint is reported if you depend on a transitive dependency. Do you have in your pubspec.yaml defined collection?

    
    dependencies:
       collection: ^1.16.0
    

    I had same issue but after defining dependency, lint issue is gone.