firebase 获取错误;没有为类型"Object?Function()"定义运算符"[]"

iaqfqrcu  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(95)

我正在使用StreamBuilder将流转换为Widgets,但是我在运算符中突出显示了字符串,并显示了错误:
The operator '[]' isn't defined for the type 'Object? Function()
这是代码:

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);
            },
          ),
d4so4syb

d4so4syb1#

.data是一个 * 函数 *。因此,您必须使用括号()来调用它。此外,您可能必须使用as关键字来转换正确的类型。
代替:

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

试试看:

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

或者:您可以使用.get()

final messageText = message.get('text');
final messageSender = message.get('sender');

相关问题