0

What's the difference between ? and ! when used in a collection in Dart?


Say, I have:

var list = [1, 2];

Now, I can either use

print(list?[0]); // prints 1

or

print(list![0]); // also prints 1

Both of them seems to do the same job, so what's the difference?

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

1

Both of them seem to do the same job because your list is of type List<int> (non-nullable) and not the List<int>? (nullable). If your list had been of nullable type like:

List<int>? list;

you'd see the difference.


Using? (Null aware operator)

It would be safe to use ? because in case list is null, list?[0] would still print null rather than throwing an error.

print(list?[0]); // Safe

or you could also use ?? to provide a default value.

print(list?[0] ?? -1); // Safe. Providing -1 as default value in case the list is null 

Using ! (Bang operator)

However, ! throws runtime error because you're explicitly saying that your list is not null and you're downcasting it from nullable to non-nullable:

print(list![0]); // Not safe. May cause runtime error if list is null

This is equivalent to

print((list as List)[0]); 
iDecode
  • 22,623
  • 19
  • 99
  • 186