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

Abd*_*man 2 firebase flutter flutter-futurebuilder

我的代码在以下错误中给出了我在此行中从 firebase 访问用户名时遇到的问题

snapshot.data['username']

它给出了上面提到的错误

我知道访问地图数据的唯一方法是这样

FutureBuilder<Object>(
  future: FirebaseFirestore.instance
   .collection('users')
   .doc(userId)
   .get(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return Text("Loading...");
    }
    return Text(
      snapshot.data['username'],
      style: TextStyle(
        fontWeight: FontWeight.bold,
      ),
    );
  }
),
Run Code Online (Sandbox Code Playgroud)

Sha*_*iya 15

在新的flutter更新中,我们不需要添加 .data()

我收到了这个错误,删除.data()后解决了。

FutureBuilder<Object>(
  future: FirebaseFirestore.instance
   .collection('users')
   .doc(userId)
   .get(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return Text("Loading...");
    }
    return Text(
      snapshot['username'],
      style: TextStyle(
        fontWeight: FontWeight.bold,
      ),
    );
  }
),
Run Code Online (Sandbox Code Playgroud)


小智 7

这个解决方案对我有用!

尝试切换

snapshot.data['username']
Run Code Online (Sandbox Code Playgroud)

(snapshot.data as DocumentSnapshot)['username']
Run Code Online (Sandbox Code Playgroud)


Joh*_*ohn 5

在较新版本的 Flutter 中,您必须将 FutureBuilder 的类型指定为 DocumentSnapshot。编辑您的代码,如下所示:

           FutureBuilder<DocumentSnapshot>(
              future: FirebaseFirestore.instance
                  .collection('users')
                  .doc(userId)
                  .get(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) 
                {
                  return const Text('Loading...');
                }
                return Text(
                  snapshot.data!['username'],
                  style: const TextStyle(fontWeight: FontWeight.bold),
                );
              }),
Run Code Online (Sandbox Code Playgroud)

这应该对你有用。