空安全问题-映射包含非空值



为什么会出现错误:

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