无法无条件调用方法“[]”,因为接收者可以是 'null' StreamBuilder

The method '[]' can't be unconditionally invoked because the receiver can be 'null' StreamBuilder

我最近将我的 flutter 升级到了最新版本,但我收到了所有空安全错误。

StreamBuilder(
stream: FirebaseFirestore.instance
  .collection('restaurants')
  .doc(partnerId)
  .snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
  return Center(
    child: CircularProgressIndicator(),
  );
}
final restaurant = snapshot.data;
startTime = restaurant['startTime'].toDate();
endTime = restaurant['endTime'].toDate();

当我将 restaurant[''] 分配给任何变量时出现以下错误。

The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

如果我这样做 - restaurant!['endTime'].toDate();,会出现新错误

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.

尝试将 snapshot.data 投射到任何你的流 returns。

示例: 如果您的流 returns a Map,这是您的代码:

StreamBuilder(
stream: FirebaseFirestore.instance
  .collection('restaurants')
  .doc(partnerId)
  .snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
  return Center(
    child: CircularProgressIndicator(),
  );
}

// dont forget to assume that your stream may
// have an error, or dont return data.
if(!snapshot.hasData) return Container();

final restaurant = snapshot.data as Map;
startTime = restaurant['startTime'].toDate();
endTime = restaurant['endTime'].toDate();

snapshot.data 是一个 AsyncSnapshot。您必须执行以下操作: Map<String, dynamic> restaurant = snapshot.data.data() 如果您得到的是单个文档。