【问题标题】:Flutter The method '[]' can't be unconditionally invoked because the receiver can be 'null'Flutter 方法\'[]\'不能无条件调用,因为receiver可以是\'null\'
【发布时间】:2022-08-15 01:37:20
【问题描述】:

我有一个错误说明\“方法\'[]\'不能被无条件地调用,因为接收者可以是\'null\'。 尝试使调用有条件(使用\'?。\')或向目标添加空检查(\'!\')。\“我尝试按照说明添加\'!\'标记并在线搜索,但它没有解决问题。有什么想法吗?

factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
    return UserModel(
      name: snapshot.data()[\"name\"],
      email: snapshot.data()[\'email\'],
      phoneNumber: snapshot.data()[\'phoneNumber\'],
      uid: snapshot.data()[\'uid\'],
      isOnline: snapshot.data()[\'isOnline\'],
      profileUrl: snapshot.data()[\'profileUrl\'],
      status: snapshot.data()[\'status\'],
      designation: snapshot.data()[\'designation\'],
      company: snapshot.data()[\'company\'],
    );
  }

    标签: flutter firebase google-cloud-firestore


    【解决方案1】:

    那是因为如果 snapshot.data()null 则您无法真正访问其字段,请尝试 null 检查它:

    snapshot.data()?['name'] ?? ''
    

    并且根据docsdata方法返回非空映射,所以你也可以试试这个:

    (snapshot.data() as Map<String,dynamic>)['name']
    

    始终假设您允许名称参数的 null 值。否则,您还需要对其进行空检查

    (snapshot.data() as Map<String,dynamic>)['name'] ?? ''
    

    【讨论】:

    • 嗨,现在错误发生在名称上
    • 你指的是哪个名字?
    • [ 'name' ] 有此错误 'The operator '[]' is not defined for the type 'Object'。尝试定义运算符'[]'。
    • 你可以试试(snapshot.data() as Map&lt;String,dynamic&gt;?) ['name'] ?? ''
    • 好的,非常感谢!!!但是,当我删除它们时,我是否需要“??''”没有错误发生
    【解决方案2】:

    你能这样试试吗

    factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
        return UserModel(
          name: snapshot.data()["name"] ?? "",
          email: snapshot.data()['email'] ?? "",
          phoneNumber: snapshot.data()['phoneNumber'] ?? 0,
          uid: snapshot.data()['uid'] ?? 0,
          isOnline: snapshot.data()['isOnline'] ?? false,
          profileUrl: snapshot.data()['profileUrl'] ?? ""
        );
      }
    

    【讨论】:

    • 你好,错误依然存在
    【解决方案3】:
    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-12-01
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 2021-09-16
      • 2022-08-24
      • 2022-08-15
      • 1970-01-01
      相关资源
      最近更新 更多