Why is there an error:
A value of type 'TestBloc?' can't be returned from the method 'createFromId' because it has a return type of 'TestBloc.
The map
contains values of type TestBloc
(not of type TestBloc?
) so it is impossible to assign a null
value.
class TestBloc {
String id;
TestBloc({
required this.id,
});
}
class TestBlocFactory {
final Map<String, TestBloc> _createdElements = HashMap<String, TestBloc>();
TestBloc createFromId(String id) {
if (_createdElements.containsKey(id)) {
return _createdElements[id]; // !! ERROR !!
} else {
TestBloc b = TestBloc(id: id);
_createdElements[id] = b;
return b;
}
}
}
2
Answers
You may define you map as
<String, TestBloc>
but still_createdElements[id]
may return anull
value, because theid
key may not available so it may returnnull
but because you check it in your if condition you can use!
(as@MendelG said) or you can cast it like this:
Since you are checking that the
map
contains the correctid
with_createdElements.containsKey
, you know for sure that it won’t returnnull
. So, it’s safe to use the!
operator which says "I won’t be null"See also
Understanding " ! " Bang Operator in dart
Understanding null safety (dart.dev)