how to suppress 'The declaration isn't referenced' Dart Analysis warning for a file?

Viewed 1513

I have a generated dart file in my project that has some unused methods -- these unused methods are causing the Dart Analysis server in Android Studio to give a warning about each unused method.

The warning looks like this: info: The declaration '<method name>' isn't referenced. (unused_element at [<app name>] lib/Models/<file name>.g.dart:<line number of method>)

How does one suppress these warnings just for the generated file?

3 Answers

From Step 5 here (the whole article is well worth reading)

Warnings in generated files do not matter to you. Generated files are out of your control. You shouldn’t edit them, and probably shouldn’t care about how the generated code looks like either. As such, instead of polluting your IDE with tons of pointless warning, simply disabling the linter on generated files is enough. This can be done by adding some code to your analysis_options.yaml. In our case, we will use both json_serializable and Freezed, so the code what we want to add is:

analyzer:
  exclude:
    # ignore warnings in files from json_serializable, built_value and most generators
    - "**/*.g.dart"
    # ignore warnings in files generated by Freezed specifically.
    - "**/*.freezed.dart"

As a workaround it can be ignored with

// ignore: unused_element
_func_dart_complains_about() {}

or

// ignore_for_file: unused_element

...

_func_dart_complains_about() {}

This is a general issue with nested functions. If you're declaring a local function within a parent function, return the same function using a return statement for the parent function.

Like in the below example, if I wouldn't return max(); inside the parent void MainMax() I'd get the error The declaration '<method name>' isn't referenced. Do check and return proper nested functions.

void mainMax(int a, int b, int c) {
  void max(){
  if(a>b && a>c){
  print (a);
  } else if (b>a && b>c){
  print (b);
  } else{ 
  print (c);
    }  
  }
max();
}
Related