Search code examples
flutterdartnullnullableelvis-operator

Why mapping nullable collection is always not null in dart?


1      factory SuggestSessionResult.fromJson(Map<String, dynamic> json) {
2        final String? error = json['error'];
3        final List<Map<String, dynamic>>? items = json['items'];
4        return SuggestSessionResult(
5          items
6            ?.map((it)=>SuggestItem.fromJson(it))
7            .toList(),
8          error
        );
      }

Hello! As you can see, I've not used null-aware operator in line 7 and that's ok for compiler. Moreover, when I use it, the analyzer says the receiver can't be null. Why so?


Solution

  • In Dart 2.12, ?. was made short-circuiting.

    From the Understanding null safety document:

    To address this, we borrowed a smart idea from C#’s design of the same feature. When you use a null-aware operator in a method chain, if the receiver evaluates to null, then the entire rest of the method chain is short-circuited and skipped.

    In your case, .map(), if called, cannot return null (because Iterable.map does not return a nullable type). Therefore .toList() either will never be called (because .map() was not called earlier in the method chain) or will be guaranteed to be called on a non-null value.