Home > Net >  The operator '[]' isn't defined for the type 'Object? Function()'. error
The operator '[]' isn't defined for the type 'Object? Function()'. error

Time:07-04

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ChatScreen extends StatefulWidget {
  static String id = 'chat_screen';

  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final _firestore = FirebaseFirestore.instance;
  final _auth = FirebaseAuth.instance;
  late String messageText;
  late User loggedInUser;

  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  void getCurrentUser() {
    try {
      final user = _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.email);
      }
    } catch (e) {
      print(e);
    }
  }

  void messageStream() async {
    await for (var snapshot in _firestore.collection('messages').snapshots()) {
      for (var message in snapshot.docs) {
        print(message.data());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                messageStream();
                // _auth.signOut();
                // Navigator.pop(context);
              }),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            StreamBuilder<QuerySnapshot>(
          stream: _firestore.collection('messages').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(
                  backgroundColor: Colors.lightBlueAccent,
                ),
              );
            }
            final messages = snapshot.data!.docs;
            List<Text> messageWidgets = [];
            for (var message in messages) {
              final messageText =
                  (message.data as Map)['text'];
              final messageSender =
              (message.data as Map)['sender'];

              final messageWidget =
                  Text('$messageText from $messageSender');
              messageWidgets.add(messageWidget);
            }
            return Column(
              children: messageWidgets,
            );
          },
        ),
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      onChanged: (value) {
                        messageText = value;
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      print(messageText);
                      _firestore.collection('messages').add(
                        {
                          'text': messageText,
                          'sender': loggedInUser.email,
                        },
                      );
                    },
                    child: Text(
                      'Send',
                      style: kSendButtonTextStyle,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

the line wherefinal messageText = message.data['text']; it throws an error The operator '[]' isn't defined for the type 'Object? Function()'. I tried reading the docs but cant understand what the problem might be. I am currently following the courseFlutter bootcamp-Angela Yu and the course is mostly outdated .I am able to solve most of the errors but I am new to firebase and don't know what to do This is the error message I am getting in android studioError in android Studio

CodePudding user response:

You could use the "get function" with that name in your documentation . It works for me.

==> message.get('text')

        List<MessgaeBubble> messageBubbles = [];
        final messages = snapshot.data?.docs.reversed;
        for (var message in messages!) {
          final messageText = message.get('text');
          final messageSender = message.get('sender');
          final currentUser = loggedInUser.email;

          if(currentUser==messageSender){

          }

          final messgaeBubble = MessgaeBubble(
              text: messageText,
              sender: messageSender,
              isMe: currentUser == messageSender,
          );
          messageBubbles.add(messgaeBubble);
        }

  • Related