Skip to content

Map does not have a null-aware-chainable "get" method #36541

Closed
@srawlins

Description

@srawlins

Take the following example:

void fn(List<Map> listOfMaps) {
  var x = listOfMaps?.elementAt(0)["key"];
}

I am accessing the first element of listOfMaps, guarding against null, with listOfMaps?.elementAt. However, if listOfMaps is null, then so is listOfMaps?.anything, so an exception will be raised when ultimately [] is called on null.

The solution to this for property access is to chain null-aware all the way down, i.e. foo?.bar.baz.quux should be foo?.bar?.baz?.quux to be safe. But this cannot be done for operators like [].

In the case of a List, you can replace list[i] with list?.elementAt(i), but there is no equivalent method for Map. I propose V get(K key) or V get(Object key).

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-core-librarySDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.library-collection

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions