Hello I have a nested list in flutter,

I try to search into the 2nd array list and if i found a response I clear this list and just add the object.

 filterSearchResults(String query) {
    List<Categorie> searchListCategorie = [];
    searchListCategorie.addAll(list);
    if (query.isNotEmpty) {
      List<Categorie> resultSearchCategorie = [];
      searchListCategorie.asMap().forEach((index, categorie) {
        List<Service> resultSearchService = [];

        categorie.service!.forEach((service) {
          if (service.name!.toLowerCase().contains(query)) {
            resultSearchService.add(service);
          }
        });

        categorie.service!.clear();
        categorie.service!.addAll(resultSearchService);
        resultSearchCategorie.add(categorie);
      });

      setState(() {
        list.clear();
        list.addAll(resultSearchCategorie);
      });
    } else {
      setState(() {
        list.clear();
        list.addAll(list2);
      });
    }
  }

this is my code, search works and I have a result but when I remove query the list didn't return in the initial state

The list is like this


  Categorie(
    name: 'TEST DEBUT',
    service: [
      Service(
          name: 'CSP1 BAT',
          indicatif: '-',
          nTPH: 'xxx',
          nVert: 'xx',
          portable: 'xx'
      ),
      Service(
          name: 'CSP2 JUSTE',
          indicatif: '-',
          nTPH: 'xxx',
          nVert: 'xxx',
          portable: 'xx'
      )
    ],
  )]

If I search CSP1 It's work he juste show me csp1 but when I remove query the list still with search value and not reset in the initial value.

Somoena can help me please ?


Solution 1: maycol99

First, are you sure you are invoking the function when the user remove the query?, if you're sure that happen, so look into the list2 content because you're adding the content in list1 when the query is empty and the list2 may be different than the list1.

Also, if you're not using null safety it's a good idea to check for possible null values in conditions.