Home > Enterprise >  Firebase Realtime Database not ordering data correctly in ListView.builder
Firebase Realtime Database not ordering data correctly in ListView.builder

Time:11-25

I am currently integrating a chat feature in my mobile app and ran into an issue when ordering Firebase Realtime Database documents by their timeStamp.

This is the code that is run on initState

  getStartData() async {
    DatabaseReference starCountRef =
        FirebaseDatabase.instance.ref('messages/${widget.placeID}');
    starCountRef
        .orderByChild("timeStamp")
        .limitToLast(6)
        .onValue
        .listen((DatabaseEvent event) {
      final data = event.snapshot.value as dynamic;
      setState(() {
        list = data.values.toList();
      });
    });
  }

This is the result

enter image description here

The issue isn't with the timeStamp property being incorrect, but with the physical rearrangement itself.

CodePudding user response:

Base on this code that i read. that you didn't implement the .onChildAdded

getStartData() async {
    DatabaseReference starCountRef =
        FirebaseDatabase.instance.ref('messages/${widget.placeID}');
    starCountRef
        .orderByChild("timeStamp")
        .limitToLast(6)
        .onValue
        .listen((DatabaseEvent event) {
      final data = event.snapshot.value as dynamic;
      setState(() {
        list = data.values.toList();
      });
    });
  }

as soon as you call final data = event.snapshot.value as dynamic that mean you convert the result, but the values in the map has no place for the relative order of result. base on this github answer for the issue.

  • Related