2

I am trying to index/extract specific elements from specific lists in a map, however, I keep getting an error on android studio that says:

"The method '[]' can't be unconditionally invoked because the receiver can be 'null'."

In this simple example I'm trying to print the letter "B" by indexing twice using two sets of []. Android studio suggests I put a ! in between the two square brackets ( i.e ["x"]![1] ), however, I don't know what that does, nor does it fix the problem. It is really frustrating because I tried this code out on replit.com and it works exactly as I intended it, however once I try it in android studio or a flutter app it doesn't work...

An explanation as to why it doesn't work and a work around would be greatly appreciated.

import "dart:core";

void main() {
  var test = {
    "x": ["A", "B", "C"],
    "z": ["D", "E", "F"],
  };

  print(test["x"][1]);
}

1 Answer 1

3

That's because you are trying to access a key in test that may not exist. What if you call test["y"][1]?

You can bypass this using two approaches:

  1. If you are sure that the key exists in the map, use the ! operator:
print(test["x"]![1]);

This is known as the "bang operator", you can read more about it here. Basically, this allows you to tell the compiler that you're sure that this value exists in the runtime. Beware that, if the value does not exist (in this case, if the key being accessed is not present in the map), a NullPointerException will be thrown.

  1. If you want to do a custom action when a key does not exists, use an additional check:
var list = test["x"];
if (list == null) {
    print("This key does not exist!");
} else {
    print(list[1]);
}

This is more verbose, but it allows you to do a custom action (such as printing a message to the user) instead of throwing an ugly error.

Sign up to request clarification or add additional context in comments.

1 Comment

test["y"]?[1] is another alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.