Home > Software engineering >  The operator '[]' isn't defined for the type 'Object'. Try defining the ope
The operator '[]' isn't defined for the type 'Object'. Try defining the ope

Time:05-17

StreamBuilder<QuerySnapshot>(
                    stream: catatan.snapshots(),
                    builder: (_, snapshot) {
                      if (snapshot.hasData) {
                        return Column(
                          children: snapshot.data.docs.map((e) =>
                                  Data(e.data()['judul'], e.data()['isi']))
                              .toList(),
                        );
                      } else {
                        return Text('Data Kosong');
                      }})

I get an error in ['judul'] and ['isi']

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

can you guys help me :)

CodePudding user response:

The data['key'] operator you want to use is only available for a Map<String, dynamic> type variable. But if not typed the method data() will return an object of type Object.

You will have to cast the result like this:

snapshot.data.docs.map<Widget>((e) {
  final data = e.data() as Map<String, dynamic>;
  return Data(data['judul'], data['isi']);
}).toList();

CodePudding user response:

Type your data to Map<String, dynamic> Refer example:

StreamBuilder<QuerySnapshot>(
              stream: catatan.snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> chatSnapshot) {
                if (chatSnapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: Container(),
                  );
                }
                return ListView(
                  controller: _controller,
                  physics: const BouncingScrollPhysics(),
                  children:
                      chatSnapshot.data!.docs.map((DocumentSnapshot document) {
                    Map<String, dynamic> data =
                        document.data()! as Map<String, dynamic>;
                    return Text(data['judul'])
                  }).toList(),
                );
              },
            ),
  • Related