2

I am turning a stream into Widgets using the StreamBuilder, but I get my string in the operator highlighted and with the error:

The operator '[]' isn't defined for the type 'Object? Function()

This is the code:

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


    body: SafeArea(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          StreamBuilder<QuerySnapshot>(
            stream: _firestore.collection('messages').snapshots(),
            builder: (context, snapshot) { //This is where the second error appeared
              if (snapshot.hasData) {
                final messages = snapshot.data?.docs;
                List<Text> messageWidgets = [];
                for (var message in messages!) {
                  final messageText = message.data['text']; //These are where the errors can be found
                  final messageSender = message.data['sender'];//These are where the errors can be found.

                  final messageWidget = Text('$messageText from $messageSender');
                  messageWidgets.add(messageWidget);
                }
                return Column(
                  children: messageWidgets,
                );
              }
              return build(context);
            },
          ),

1 Answer 1

2

.data is a function. So, you have to call it using parenthesis (). Additionally, you might have to cast the correct type using the as keyword.

Instead of:

final messageText = message.data['text'];
final messageSender = message.data['sender'];

Try:

final messageText = (message.data() as Map)['text'];
final messageSender = (message.data() as Map)['sender'];

Or: you can use .get():

final messageText = message.get('text');
final messageSender = message.get('sender');
Sign up to request clarification or add additional context in comments.

2 Comments

I have edited my question it is about the last line of code where I return build(context), initially I had an error saying; "The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type" so I decided to do return build(context)... am I correct about this? or what should I have done if I wasn't
@Fred_Wolfe Yes, you should add the return keyword to fix that error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.