Home > Net >  Firebase Sorting is not working properly in flutter
Firebase Sorting is not working properly in flutter

Time:06-08

I'm developing a course app in flutter. so there is a subcollection for displaying episodes inside the course. and I'm sending episode numbers when creating the episodes to sort the episode with the value using the firebase orderBy function. it's working but not ordering properly. (what I mean by working is it's sorting differently but messed up).

here are all codes and details

Read Episode code

  @override
  Stream<List<EpisodesModel>> readEpisode({
    required id,
  }) {
    return FirebaseFirestore.instance
        .collection('courses')
        .doc(id)
        .collection('eps')
        .orderBy('episodeNum', descending: false) // the eps num is the number that I send to firebase db when creating course 
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map((doc) => EpisodesModel.fromJson(doc.data()))
            .toList());
  }

but this is how the value is sorting

enter image description here

please comment if any other code is needed,

CodePudding user response:

It looks like the values in your episodeNum field are stored as string values, and not as numbers. And in the lexicographical ordering (which Firestore uses for string values) "10" comes before "2", just as "aa" comes before "b".

To fix the problem, store the episodeNum values as numbers in the database, and Firestore will order them correctly.

  • Related