为什么会出现错误:
A value of type 'TestBloc?' can't be returned from the method 'createFromId' because it has a return type of 'TestBloc.
map
包含TestBloc
类型的值(不包含TestBloc?
类型的值),因此不可能分配null
值。
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;
}
}
}
由于您正在检查map
是否包含正确的id
和_createdElements.containsKey
,因此您肯定知道它不会返回null
。因此,使用!
运算符是安全的它表示&;我不会为空&;
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]!;
} else {
TestBloc b = TestBloc(id: id);
_createdElements[id] = b;
return b;
}
}
}
参见
理解"! ";空格
中的空格操作符了解null安全(part .dev)
您可以将您的映射定义为<String, TestBloc>
,但仍然_createdElements[id]
可能返回null
值,因为id
键可能不可用,所以它可能返回null
,但是因为您在if条件中检查它,您可以使用!
(as)@MendelG说)或者你可以像这样投射它:
if (_createdElements.containsKey(id)) {
return _createdElements[id] as TestBloc; // <--- change this
} else {
TestBloc b = TestBloc(id: id);
_createdElements[id] = b;
return b;
}