Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'

My code is given below the error I am facing issue in accessing the username from firebase in this line

snapshot.data['username']

It gives the error mentioned above

The only way I know to access the map data is this

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,
      ),
    );
  }
),
like image 715
Abd ur Rehman Avatar asked Feb 07 '21 10:02

Abd ur Rehman


2 Answers

In the new flutter update, we don't need to add .data()

I got this error and after removing .data() it was solved.

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,
      ),
    );
  }
),
like image 150
Shamil Keheliya Avatar answered Dec 23 '22 15:12

Shamil Keheliya


In the newer versions of Flutter you have to specify the type for FutureBuilder as DocumentSnapshot. Edit your code like below:

           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),
                );
              }),

This should work for you.

like image 27
John Avatar answered Dec 23 '22 14:12

John