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);
},
),
CodePudding user response:
.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');