Sdk: Null aware access operators don't support maps.

Created on 10 Nov 2015  路  6Comments  路  Source: dart-lang/sdk

If I try to access a map value of a possibly null class, it will blow up.
Sample code:

void main() {
  // "if null" operator
  print(null ?? 'New in Dart 1.12');

  // null-aware method invocation
  var isNull = null;
  print(isNull?.foo()); // Works
  print(isNull?.foo['test']); // Blows up
}

Dartpad:
https://dartpad.dartlang.org/0593a864be7d75cd2da1

Dart2JS produces this obscure error:
Uncaught TypeError: C.JSNull_methods.$index is not a function

In the VM it's much more clear what is happening:
The null object does not have a method '[]'

This occurs with Dart 1.12.2 and bleeding_edge

area-sdk closed-as-intended

Most helpful comment

Just FYI, the following program works fine when the not yet released non-null-by-default feature (aka NNBD) is turned on:

main() {
  Map? map = null;
  map?.[3] = "Unused";
  print(map?.[3]);
}

So 'closed-as-intended' was true in 2015, but things have been moving since then and the null-aware index operators will be available along with NNBD.

All 6 comments

runtime error: The null object does not have a method '[]'

ah, thanks!

I don't see the bug.

Looking at your statement, isNull?.foo['test'] first evaluates isNull?.foo (null-aware access), which evaluates to null. Then it evaluates null['test'], but The null object does not have a method '[]'.

I think maybe you are expecting null-aware map lookup?, like isNull?.foo?['test'], which is not a thing.

I suppose I am expecting the null-aware map lookup, but without the extra null check. I guess that comes down to not anticipating [] as an operator.
Thanks for the reference to that discussion, I hadn't noticed it previously.

Null aware map lookup would be a great feature to have built in, e.g. when destructuring json into objects.

The linked thread mentions adding get and add methods to map, since null aware access exists, allowing name = json.get('attributes')?.get('name').

I plan to work around by adding get and add on Map via extension method.

Just FYI, the following program works fine when the not yet released non-null-by-default feature (aka NNBD) is turned on:

main() {
  Map? map = null;
  map?.[3] = "Unused";
  print(map?.[3]);
}

So 'closed-as-intended' was true in 2015, but things have been moving since then and the null-aware index operators will be available along with NNBD.

Was this page helpful?
0 / 5 - 0 ratings