我有一个消息列表,我想在其中添加一个Firebase集合。

import 'package:flutter/material.dart';
import 'package:my_first_flutter_app/chatmessage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:logging/logging.dart';
final Logger log = new Logger('ChatScreen');

class ChatScreen extends StatefulWidget {
  @override
  State createState() => new ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> {
  final TextEditingController _chatController = new TextEditingController();
  final List<ChatMessage> _messages = <ChatMessage>[];

  @override
  Widget build(BuildContext context) {

    return new Column(
      children: <Widget>[
        new Flexible(
          child: ListView.builder(
            padding: new EdgeInsets.all(8.0),
            reverse: true,
            itemBuilder: (_, int index) => _messages[index],
            itemCount: _messages.length,
          ),
        ),
        new Divider(
          height: 1.0,
        ),
        new Container(decoration: new BoxDecoration(
          color: Theme.of(context).cardColor,
        ),
          child: _chatEnvironment(),)
      ],
    );
  }
}

我试图这样做:
@override
  Widget build(BuildContext context) {
    Firestore.instance
        .collection('chats')
        .document('ROOM_1')
        .collection("messages")
        .getDocuments()
        .then((snap) {
      return new Column(
         ....

但是我需要返回一个Widget,而此尝试返回的是Future

如何在我的聊天屏幕页面的初始化中,使用来自Firestore集合的数据填充_messages数组?

最佳答案

如果您只需要在firestore集合的ListView中显示所有消息,那么您可能会喜欢StreamBuilder小部件。您可以执行以下操作:

return new Column(
  children: <Widget>[
    new Flexible(
      child: StreamBuilder(
        stream: Firestore.instance.collection('chats').document('ROOM_1').collection('messages').snapshots(),
        builder: (context, snapshot){
          if (!snapshot.hasData){
            return Container(
              child: Center(
                child: Text("No data")
              )
            );
          }

          return ListView.builder(
            padding: EdgeInsets.all(8.0),
            reverse: true,
            itemCount: snapshot.data.documents.length,
            itemBuilder: (_, int index) {
              return ChatMessage(text: snapshot.data.documents[index]["messageField"]); //I just assumed that your ChatMessage class takes a parameter message text
            }
          );
        }
      )

    ),
    new Divider(
      height: 1.0,
    ),

    ...

请注意,在此示例中,我没有使用_messages变量。

关于dart - Flutter-用Firebase集合填充列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53977191/

10-12 05:23