flutter 空安全问题-Map包含不可为空的值

c0vxltue  于 2022-12-30  发布在  Flutter
关注(0)|答案(2)|浏览(449)

为什么会出现错误:

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

qxsslcnc1#

由于您要检查map是否包含正确的id_createdElements.containsKey,因此您肯定知道它不会返回null,因此使用!操作符是安全的,该操作符表示"I won't be 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;
    }
  }
}
另请参见
hk8txs48

hk8txs482#

您可以将map定义为<String, TestBloc>,但_createdElements[id]仍然可以返回null值,因为id键可能不可用,所以它可能返回null,但因为您在if条件中选中了它,所以可以使用!(如@MendelG所述),或者可以将其转换为如下形式:

if (_createdElements.containsKey(id)) {
  return _createdElements[id] as TestBloc; // <--- change this
} else {
  TestBloc b = TestBloc(id: id);
  _createdElements[id] = b;
  return b;
}

相关问题