无法访问颤振中的 Firebase Firestore 文档的字段

时间:2021-05-17 06:13:22

标签: firebase flutter google-cloud-firestore

我想访问文档字段,为此我使用了以下代码,但出现错误:-

The operator '[]' isn't defined for the type 'Object'. (Documentation)

我的 Cloud Firestore 版本是 cloud_firestore: ^2.1.0

我的代码:-

import 'package:cloud_firestore/cloud_firestore.dart';

class TeamModel
{
  final String id;
  final String name;
  final String url;
  final String category;
  final String role;

  TeamModel({
    this.id,
    this.name,
    this.url,
    this.category,
    this.role
  });

  factory TeamModel.fromDocument(DocumentSnapshot doc)
  {
    return TeamModel(
      id: doc.id,
      name: doc.data()['name'],// I am getting the error on this ['name']
      url: doc.data()['url'], // same error here
      category: doc.data()['category'],// same error here
      role: doc.data()['role'],// same error here
    );
  }
}

1 个答案:

答案 0 :(得分:1)

在没有 .data()

的情况下试试这个
factory TeamModel.fromDocument(DocumentSnapshot doc)
  {
    return TeamModel(
      id: doc.id,
      name: doc['name'],
      url: doc['url'],
      category: doc['category'],
      role: doc['role'],
    );
  }