没有为类型“Object”定义运算符“[]”。尝试定义运算符 '[]' 错误

时间:2021-05-11 11:43:42

标签: flutter dart

body: Center(
    child: Container(
      height: 300,
      width: 300,
      //color: Colors.black,
      child: StreamBuilder<QuerySnapshot>(
        stream: firestore.collection("users").snapshots(),
        builder: (context, snapshot) {
          if (snapshot == ConnectionState.waiting) {
            return CircularProgressIndicator();
          } else {
            return new ListView(
              children: snapshot.data!.docs.map((DocumentSnapshot documentSnapshot){
                return Card(
                  child: Text(documentSnapshot.data()!["Name"]),
                );
              }).toList(),
            );
          }
        },
      ),
    ),
  ),

["Name"] 显示错误 未为类型“Object”定义运算符“[]”。尝试定义运算符“[]”。

2 个答案:

答案 0 :(得分:1)

您需要将 documentSnapshot.data() 转换为 DocumentSnapshot 正确的类型:

(documentSnapshot.data() as DocumentSnapshot)["Name"]

答案 1 :(得分:0)

你需要像这样投射:

(documentSnapshot.data() as Map<String, dynamic>)['Name']