【问题标题】:The method '[]' can't be unconditionally invoked because the receiver can be 'null' | Firebase Database | Flutter方法\'[]\'不能被无条件调用,因为接收者可以是\'null\' | Firebase 数据库 |扑
【发布时间】:2022-08-15 01:58:59
【问题描述】:

我收到错误 The method \'[]\' can\'t be unconditionally invoked because the receiver can be \'null\'. Try making the call conditional (using \'?.\') or adding a null check to the target (\'!\'). 下面是我的代码

import \'package:firebase_database/firebase_database.dart\';

class Users {
  String? id;
  String? email;
  String? name;
  String? phone;
  Users({
    this.id,
    this.email,
    this.name,
    this.phone,
  });

  Users.fromSnapshot(DataSnapshot dataSnapshot) {
    id = dataSnapshot.key!;
    email = dataSnapshot.value[\'email\'];
    name = dataSnapshot.value[\'name\'];
    phone = dataSnapshot.value[\'phone\'];
  }
}

错误在最后 3 行

email = dataSnapshot.value[\'email\'];
name = dataSnapshot.value[\'name\'];
phone = dataSnapshot.value[\'phone\'];

我已经添加了空安全运算符。但它仍然显示错误。

标签: firebase flutter dart firebase-realtime-database flutter-dependencies


【解决方案1】:

DataSnapshot 对象不一定有值,因此其value 属性可能为空。在尝试从中读取属性之前,您需要检查快照是否具有值:

Users.fromSnapshot(DataSnapshot dataSnapshot) {
  id = dataSnapshot.key!;
  if (dataSnapshot.value != null) {
    email = dataSnapshot.value!['email'];
    name = dataSnapshot.value!['name'];
    phone = dataSnapshot.value!['phone'];
 }
}

请注意添加的 if 语句,以及 Pokaboom 也评论过的 ! 标记。

【讨论】:

    【解决方案2】:
    1. 为您的构建器设置类型
    2. 创建变量并分配snapshot.data!
    3. 使用不带任何?! 的变量。与[] 一样简单的列表
      FutureBuilder<List<Orders>>(                         // 1
         future: futureOrders,
         builder: (context, snapshot) {
            if (!snapshot.hasData) {
               return const Center(child: CircularProgressIndicator());
            } else {
               final List<Orders> orders = snapshot.data!; // 2
               return ListView.builder(
                  itemCount: orders.length,                // 3
                  itemBuilder: (context, index) => _cartItemWidget(
                     id: orders[index].id,                 // 3
                     cost: orders[index].cost,             // 3
                     date: orders[index].createdAt));      // 3
            }
         },
      )
      

    【讨论】:

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