Firebase does not sort list by date correctly

Asked

Viewed 138 times

-1

I am filtering some documents by date/time to retrieve the latest items first.

However, when adding a new item to the list it is added correctly, but when restarting the app the list is redone and the items are arranged randomly, which should not be happening because I am ordering by date.

This might be how I’m adding these items to the list.

I’m doing like this:

Future<void> _addListernerFavoritos() async{
  favoritosModel.limparLista();
  List<String> listaBackp = [];

  //aqui é o listen dos meus favoritos
  //onde deveria está filtrando pela data corretamente
  //quando adiciono um favorito novo ele organiza certinho
  //o problema é quando reinicio o app ai que os itens são ordenados de forma aleatória
  FirebaseFirestore.instance
      .collection("usuarios")
      .doc(usuario.idUsuario)
      .collection("favoritos")
      .orderBy("data", descending: true)
      .snapshots()
      .listen((snapshot) {

    snapshot.docChanges.forEach((change) async{
      String idEmpresa = change.doc.id;

      switch (change.type) {
        case DocumentChangeType.added:
        //========== quando um favorito for adicionado ==========

          DocumentSnapshot docEmp = await FirebaseFirestore.instance
              .collection("empresas")
              .doc(idEmpresa)
              .get();

          Empresa empresa = Empresa.fromDocumentSnapshot(docEmp);
          if(!favoritosModel.listFavoritos.contains(empresa)){
            //favoritosModel.addFavoritos(empresa);
            favoritosModel.insertFavorito(0, empresa);
          }

          break;
        case DocumentChangeType.modified:
        //========== modificado ==========
          break;
        case DocumentChangeType.removed:
        //========== removido ==========
          favoritosModel.removeWhere(idEmpresa);
          listaBackp.add(idEmpresa);
          break;
      }
    });

    //_sort();
  });
}

The model I’m using to update the list is this:

class FavoritosModel = _FavoritosModel with _$FavoritosModel;

abstract class _FavoritosModel with Store{

  @observable
  ObservableList<Empresa> listFavoritos = ObservableList();

  @action
  void insertFavorito(int index, Empresa value){
    listFavoritos.insert(index, value);
  }

  @action
  void addFavoritos(Empresa value) {
    listFavoritos.add(value);
  }

  @action
  void removeWhere(String idEmpresa){
    listFavoritos.removeWhere((empresa) => idEmpresa == empresa.idEmpresa);
  }

  @action
  void limparLista(){
    listFavoritos.clear();
  }

  @action
  void attEmpresa(int index, Empresa value){
    listFavoritos.removeWhere((empresa) => empresa.idEmpresa == value.idEmpresa);
    listFavoritos.insert(index, value);
  }

}

My listview looks like this:

@override
  Widget build(BuildContext context) {

    return Container(
      color: Cores.COR_CINZA_BACKGROUND,
      child: Observer(
        builder: (_){
          FavoritosModel favoritosModel = GetIt.I<FavoritosModel>();
          ObservableList<Empresa> listFavoritos = favoritosModel.listFavoritos;

          if(listFavoritos.length == 0){
            return Container(
              margin: EdgeInsets.only(left: 16, right: 16),
              child: Center(
                child: TextApp(
                  text: "Você ainda não adicionou nenhuma empresa aos favoritos",
                  fontSize: 16,
                  textColor: Cores.COR_DARK_LIGTH,
                  fontFamily: "OpenSans",
                  centralizar: true,
                ),
              ),
            );
          }
          return ListView.builder(
            //reverse: true,
            itemCount: listFavoritos.length,
            itemBuilder: (context, index){

              Empresa empresa = listFavoritos[index];

              if(empresa == null){
                return Container();
              }

              return GestureDetector(
                onTap: (){
                  push(context, TelaEmpresa(empresa: empresa));
                },
                  child: CardEmpresa(empresa: empresa, favoritos: true,));
            },
          );

        },
      ),
    );

  }

The way I see it, it’s all right, I don’t understand why you’re not ordering by date. Could someone help me?

I’ve tried to save the date of these two ways and none of it works:

Timestamp getDataFiltro(){
  var now = new Timestamp.now();
  return now;
}

String getDateNow(){
  var now = new DateTime.now();
  return now.toString();
}
  • Hello, I got the suspicion that you could call favoritesModel.Sort(); just once, right after the switch()

1 answer

0


Problem Solved.

To solve this problem I had to call the favoritosModel.sort(); in all changes of Listen.

Below I leave the Listen with the changes made to help new people who have this same problem:

Future<void> _addListernerFavoritos() async{
    favoritosModel.limparLista();
    List<String> listaBackp = [];

    FirebaseFirestore.instance
        .collection("usuarios")
        .doc(usuario.idUsuario)
        .collection("favoritos")
        .orderBy("data", descending: true)
        .snapshots()
        .listen((snapshot) {

      snapshot.docChanges.forEach((change) async{
        String idEmpresa = change.doc.id;
        Timestamp dataFiltro = change.doc["data"];

        switch (change.type) {
          case DocumentChangeType.added:
          //========== quando um favorito for adicionado ==========

            DocumentSnapshot docEmp = await FirebaseFirestore.instance
                .collection("empresas")
                .doc(idEmpresa)
                .get();

            Empresa empresa = Empresa.fromDocumentSnapshot(docEmp);
            empresa.dataFiltro = dataFiltro;
            if(!favoritosModel.listFavoritos.contains(empresa)){
              //favoritosModel.insertFavorito(0, empresa);
            }
            favoritosModel.addFavoritos(empresa);

            favoritosModel.sort();
            break;
          case DocumentChangeType.modified:
          //========== modificado ==========
            favoritosModel.sort();
            break;
          case DocumentChangeType.removed:
          //========== removido ==========
            favoritosModel.removeWhere(idEmpresa);
            favoritosModel.sort();
            listaBackp.add(idEmpresa);
            break;
        }
      });

      favoritosModel.sort();
    });

 }
  • 6

    Young man, welcome to Stackoverflow... I’m not going to "downvote", I speak with the greatest humility in the world... when we put out some question with reward, the cool joke is: Let the crowd answer. You answered your own question before the deadline, it breaks the joke because someone might be studying your problem, even though I’m not an expert on Firebase to help you. Even if you have solved, now lost the "grace" of someone responding, including with a better solution.

  • Hello Matthew, sorry about that. I’m new here. But any and all improvement will be very welcome. I appreciate your attention, but I couldn’t wait too long to solve this problem because I have delivery time. Thanks for your help and any suggestions I’ll be here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.