Home > Enterprise >  how to transform the method from Firestore to Realtime Database
how to transform the method from Firestore to Realtime Database

Time:12-30

im trying to convert database from firestore to firebase rtdb, by the tutorial I see the following code:

  static Stream<List<Message>> getMessages(String idUser) =>
      FirebaseFirestore.instance
          .collection('chats/$idUser/messages')
          .orderBy(MessageField.createdAt, descending: true)
          .snapshots()
          .transform(Utils.transformer(Message.fromJson));

here is the code I updated:

    static Stream<List<Message>> getMessages(String idUser) =>
  FirebaseDatabase.instance
      .ref()
      .child('chats/$idUser/messages')
      .onValue
      .map((message) =>
      message.snapshot.children.map((e) =>
          Message.fromJson(e.value as Map<String, dynamic>)).toList());

is it correct and how to add method orderBy, or please share me the correct code which has same value as the one for firestore, thanks a lot!

CodePudding user response:

Firebase Realtime Database only support ascending ordering, so you can map .orderBy(MessageField.createdAt, descending: true) from Firestore to Realtime Database.

The closest you can get is:

FirebaseDatabase.instance
    .ref()
    .child('chats/$idUser/messages')
    .orderByChild(MessageField.createdAt)
    .onValue
    ...

And then reversing the results in your application code.

Also see the FlutterFire documentation on querying Realtime Database.

  • Related