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]);