【问题标题】:The method '[]' can't be unconditionally invoked because the receiver can be 'null' StreamBuilder [duplicate]无法无条件调用方法“[]”,因为接收者可以是“null”StreamBuilder [重复]
【发布时间】:2021-08-27 08:26:32
【问题描述】:

我最近将我的 Flutter 升级到了最新版本,但我遇到了所有 null 安全错误。

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!['endTime'].toDate();,就会出现新错误

没有为“对象”类型定义运算符“[]”。尝试定义 运算符“[]”。

【问题讨论】:

    标签: flutter dart google-cloud-firestore nullable


    【解决方案1】:

    尝试将snapshot.data 转换为您的流返回的任何内容。

    示例: 如果您的流返回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.docs 上遇到了类似的错误 - final documents = snapshot.data!.docs;
    • 好吧,您可以使用相同的方法,final documents = snapshot.data!.docs as Map;,但将 Map 替换为任何文档的数据类型
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2021-09-05
      • 2021-10-05
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2021-09-18
      • 2022-08-24
      相关资源
      最近更新 更多