【问题标题】:The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]' error in stream builder运算符 \'[]\' 没有为类型 \'Object\' 定义。尝试在流生成器中定义运算符 \'[]\' 错误
【发布时间】:2023-01-07 19:47:39
【问题描述】:

我收到以下错误:未为类型“对象”定义运算符“[]”。 尝试定义运算符 '[]' The part where error is coming is highlighted here

流的代码是这样的

StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection('Users')
                    .doc(FirebaseAuth.instance.currentUser?.uid)
                    .collection('Coins')
                    .snapshots(),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (!snapshot.hasData) {
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                  return ListView(

                    children: snapshot.data!.docs.map((document) {
                      return Container(
                        
                        child: Row(
                          children: [
                            
                            Text("Coin type: ${document.id}"),
                            
                            Text("Amount Owned: ${document.data()!['Amount']}"),
                          ],
                        ),
                      );
                    }).toList(),
                  );
                }),

【问题讨论】:

    标签: flutter firebase dart


    【解决方案1】:

    你可以使用as Map?

    Text(
        "Amount Owned: ${(document.data() as Map?)?['Amount']}"),
    

    更多关于dart和reading data from firestore。

    【讨论】:

    • 是的,它起作用了,谢谢,你能解释一下为什么它起作用吗:)
    • data() 返回 Object? 数据类型,虽然它是我们知道的映射,但我们使用 as 前缀,告诉编译器它是 Map? .. ? 表示可为空的数据类型
    • 为什么我们必须把它写成地图?当我以前把它写成地图时它给出了错误
    • 当我们不知道它会返回什么(IMO)时,使用 making nullable dataType 是安全的,
    • 明白谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2021-06-11
    • 2021-10-07
    相关资源
    最近更新 更多