如何从 Streambuilder 订购项目

Wil*_*son 3 dart flutter google-cloud-firestore

我正在使用 Cloud Firestore 创建一个简单的应用程序,我在其中输入文本并将其添加到列表中。

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _txtCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: SafeArea(
          child: Column(
            children: <Widget>[
              Container(
                  child: Row(children: <Widget>[
                Expanded(child: TextField(controller: _txtCtrl)),
                SizedBox(
                    width: 80,
                    child: OutlineButton(
                        child: Text("Add"),
                        onPressed: () {
                          Firestore.instance
                              .collection('messages')
                              .document()
                              .setData({'message': _txtCtrl.text});
                        })),
              ])),
              Container(
                height: 400,
                child: StreamBuilder<QuerySnapshot>(
                  stream: Firestore.instance.collection('messages').snapshots(),
                  builder: (BuildContext context,
                      AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasError)
                      return new Text('Error: ${snapshot.error}');
                    switch (snapshot.connectionState) {
                      case ConnectionState.waiting:
                        return new Text('Loading...');
                      default:
                        return new ListView(
                          children: snapshot.data.documents
                              .map((DocumentSnapshot document) {
                            return new ListTile(
                              title: new Text(document['message']),
                            );
                          }).toList(),
                        );
                    }
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

一切正常,但 Streambuilder 中的项目列表是随机排列的。

我知道这是因为列表中的数据被 .map 函数映射(因为映射没有顺序)。

如何在不调用 .map 函数的情况下在 StreamBuilder 中按照将项目添加到我的数据库的顺序显示这些项目?

mal*_*m91 6

为文档设置数据时添加时间戳;

Firestore.instance.collection('messages').add({
  'message': _txtCtrl.text,
  'timestamp': FieldValue.serverTimestamp(),
});
Run Code Online (Sandbox Code Playgroud)

并在获取数据时使用 orderBy; Firestore.instance.collection('messages').orderBy('timestamp').snapshots();