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;
}
}
}