Faced following error for querying "The operator '[]' isn't defined for the type 'Object'."


I faced the above error while coding the chat screen which will display realtime chats with another user, for my chat app.

class _ChatState extends State<Chat> {   late Stream <QuerySnapshot<Object?>> chats;   late QuerySnapshot<Map<String, dynamic>> snapshot;   TextEditingController messageEditingController = new TextEditingController();

  Widget chatMessages() {
    return StreamBuilder<QuerySnapshot>(
      stream: chats,
      builder: (context, snapshot) {
        return snapshot.hasData
            ? ListView.builder(
                itemCount: snapshot.data?.docs.length,
                itemBuilder: (context, index) {
                  return MessageTile(
                    message: snapshot.data?.docs[index].data()!["message"],     //error line
                    sendByMe: Constants.myName ==
                        snapshot.data?.docs[index].data()!["sendBy"],           //error line
            : Container();
    );   }

  addMessage() {
    if (messageEditingController.text.isNotEmpty) {
      Map<String, dynamic> chatMessageMap = {
        "sendBy": Constants.myName,
        "message": messageEditingController.text,
        'time': DateTime.now().millisecondsSinceEpoch,

      DatabaseMethods().addMessage(widget.chatRoomId, chatMessageMap);

      setState(() {
        messageEditingController.text = "";


I would be pleased if anybody help me out and also explain to me why it is happening.


In general, this answer helps. Briefly: "You cannot call an indexer [] on an Object".

In your case, you cannot use the indexer on the objects in the two lines. A possible way to solve this could be to cast the objects to a Map or a List and apply the indexer afterwards.

Something like:

var list = snapshot.data? as List;
var map = list[index] as Map;

and then:

message: map["message"]

This is an idea. You will probably have to tweak it a bit to make it work.

Answered By – maxmitz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published