简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM