Flutter:StreamBuilder(使用Firebase实时数据库)中的项目随机排序 [英] Flutter: Items in StreamBuilder(Using firebase realtime database) are sorted randomly

查看:107
本文介绍了Flutter:StreamBuilder(使用Firebase实时数据库)中的项目随机排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase Realtime数据库创建一个简单的应用程序,用户在该数据库中输入文本并将其添加到聊天列表中。

I'm creating a simple application with Firebase Realtime database where a user inputs a text and it gets added to a list of chats.

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  var _firebaseRef = FirebaseDatabase().reference().child('chats');
  TextEditingController _txtCtrl = TextEditingController();

  @override
  Widget build(BuildContext context) {
    var comments = _firebaseRef.orderByChild('time').limitToLast(10);
    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: () {
                          sendMessage();
                        }))
              ])),
              StreamBuilder(
                stream: comments.onValue,
                builder: (context, snap) {
                  if (snap.hasData &&
                      !snap.hasError &&
                      snap.data.snapshot.value != null) {
                    Map data = snap.data.snapshot.value;
                    List item = [];

                    data.forEach(
                        (index, data) => item.add({"key": index, ...data}));

                    return Expanded(
                      child: ListView.builder(
                        itemCount: item.length,
                        itemBuilder: (context, index) {
                          return ListTile(
                            title: Text(item[index]['message']),
                          );
                        },
                      ),
                    );
                  } else
                    return Center(child: Text("No data"));
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  sendMessage() {
    _firebaseRef.push().set({
      "message": _txtCtrl.text,
      'time': DateTime.now().millisecondsSinceEpoch
    });
  }


}

它存储并完美地检索数据。但是,当我尝试添加数据时,新项目将被随机放置在列表中。

It stores and retrieves data perfectly. But when I try adding data, the new items are placed at random points in the list.

例如,在下图中,我放置在列表中的最后一个项目是九。但是它被放在列表的中心:

For example, in the image below, the last item I placed into the list was 'Nine'. But it was put in the center of the list:

我尝试按时间戳对列表进行排序,但是它什么也没做。

I've tried sorting the list by timestamps, but it did nothing.

是什么原因导致此问题?以及我该如何解决?

What could be causing this issue? And how can I fix it?

推荐答案

调用 snap.data.snapshot.value; 快照中的数据(排序)被转换为 Map< String,Object> 订购。为了维持顺序,您需要收听 onChild ...

When you call snap.data.snapshot.value; the data in the snapshot (which is ordered) is converted to a Map<String, Object> which isn't ordered. To maintain the order, you'll want to listen to onChild... instead.

请注意,FlutterFire具有便捷的 firebase_list 可处理 onChild ... 的大部分繁重工作您。

Note that FlutterFire has a convenient firebase_list library that handles most of the heavy lifting of onChild... for you.

另请参见:

  • Flutter Firebase Database wrong timestamp order
  • Flutter sort Firebase snapshot by timestamp
  • Flutter: Firebase Real-Time database orderByChild has no impact on query result

这篇关于Flutter:StreamBuilder(使用Firebase实时数据库)中的项目随机排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆