Avoid "value can be null" warning for extension method

1.1k Views Asked by At

I am using an extension on Iterable that adds the following two methods

extension MyIterableExt<T> on Iterable<T> {
  bool get isEmptyOrNull => this == null || this.isEmpty;
  bool get isNotEmptyOrNull => this != null && this.isNotEmpty;
}

This works as I expected, but when I try to use it in statements where the receiver can be null, I get a warning in IntelliJ. For example, the following code works and prints true:

List<String> x;
print('${x?.reversed.isEmptyOrNull}');

Is there any way I can make the Dart Analyzer understand that the extension checks if this == null and thus not show the warning?

Please note that I do not want to have to add suppression directives to every file or line where I use this extension!

I know I can add // ignore_for_file: can_be_null_after_null_aware or // ignore: can_be_null_after_null_aware to make the warning go away, but what I'm looking for is a way to make the Dart Analyzer understand that the warning for this particular extension method is not needed.

This is in a non null-safe project, if that matters.

3

There are 3 best solutions below

3
triple7 On

Based on the Flutter docs, you should be able to add a comment at the top of your code that will essentially disable null safety checks:

// @dart=2.9
import 'src/my_app.dart';

main() {
  //...
}

You should be able to put that comment at the top of any specific file you want this behavior. It doesn't have to be in your "main" file.

0
Hooman On

you can make Iterable Nullable

extension MyIterableExt<T> on Iterable<T>? {
  bool get isEmptyOrNull => this == null || this!.isEmpty;
  bool get isNotEmptyOrNull => this != null && this!.isNotEmpty;
}
0
Tuan On

Make extension base on Iterable? is the way, if you have to find something to disable the warning but not want to change the code then im sorry cause i never do that before.

void main() {
  Iterable? a = [];
  Iterable b = ['1', '2', '3'];
  
  print('a.isEmptyOrNull: ${a.isEmptyOrNull}');
  print('b.isEmptyOrNull: ${b.isEmptyOrNull}');
  print('a.isNotEmptyOrNull: ${a.isNotEmptyOrNull}');
  print('b.isNotEmptyOrNull: ${b.isNotEmptyOrNull}');
}

extension on Iterable? {
  bool get isEmptyOrNull => this == null || this!.isEmpty;
  bool get isNotEmptyOrNull => this != null && this!.isNotEmpty;
}

result

a.isEmptyOrNull: true
b.isEmptyOrNull: false
a.isNotEmptyOrNull: false
b.isNotEmptyOrNull: true