Home > database >  Filtering a list in Flutter with GetX with where and contains works but filtered out items don'
Filtering a list in Flutter with GetX with where and contains works but filtered out items don'

Time:01-27

I am building my first Flutter app and I am trying to filter a list of TreeTypes in Flutter with GetX using a TextFormField.

So the list is pulled from an API and I want to filter it in realtime using the TreeTypeController.filterTreeTypes(earchString) method.

It works in part. The results that do not contain the searchString are filtered out like they should but when I use backspace on the searchString, the removed items are not put back into the list.

I understand that I somehow need to make a clone of filteredTreeTypeList instead of filtering that and then overwriting it with the results but I just can't figure out how to do that. I have tried creating a new List with map and other ways I found on the interwebs but I keep getting the same problem.

Can someone please show me how to do it? Thank you!

Below are my GetxController and my view/screen.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:bonsai_care_app/services/tree_type_service.dart';
import 'package:bonsai_care_app/models/tree_type.dart';

class TreeTypeController extends GetxController {
  dynamic arguments = Get.arguments;
  var treeTypeList = <TreeType>[].obs;
  var isLoaded = true.obs;

  @override
  void onInit() {
    super.onInit();
    fetchAndSetTreeTypeList(arguments);
  }

  void filterTreeTypes(searchString) {
    var filteredTreeTypeList = [];
    filteredTreeTypeList = treeTypeList
        .where((element) =>
            element.name.toLowerCase().contains(searchString.toLowerCase()))
        .toList();
    print(filteredTreeTypeList.length);
    treeTypeList(filteredTreeTypeList);
  }

  Future<void> fetchAndSetTreeTypeList(arguments) async {
    debugPrint('TreeTypesController fetchTreeTypes()');
    try {
      isLoaded(false);
      var tree_types = await TreeTypeService().fetchTreeTypes(arguments);
      if (tree_types != null) {
        treeTypeList(tree_types);
      }
    } catch (error) {
      debugPrint(error);
      throw (error);
    } finally {
      isLoaded(true);
    }
  }
}

import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:bonsai_care_app/controllers/tree_type_controller.dart';
import 'package:bonsai_care_app/views/select_tree_type_details_screen.dart';

class SelectTreeTypeResultsScreen extends StatelessWidget {
  final TreeTypeController treeTypeController = Get.put(TreeTypeController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('select_tree_type_results__heading'.tr),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Obx(
            () {
              return Column(
                children: [
                  Container(
                    child: TextFormField(
                      onChanged: (query) {
                        treeTypeController.filterTreeTypes(query);
                      },
                      decoration: InputDecoration(
                        labelText:
                            'select_tree_type_results__search_input_label'.tr,
                        border: const OutlineInputBorder(),
                      ),
                    ),
                  ),
                  Container(
                    height: 500,
                    width: 200,
                    child: Visibility(
                      visible: treeTypeController.isLoaded.value,
                      replacement: Center(
                        child: CircularProgressIndicator(),
                      ),
                      child: treeTypeController.treeTypeList.length == 0
                          ? Center(
                              child: Text('no_results'.tr),
                            )
                          : ListView.builder(
                              itemCount: treeTypeController.treeTypeList.length,
                              itemBuilder: (context, index) {
                                return ListTile(
                                  title: Text(treeTypeController
                                      .treeTypeList[index].name),
                                  onTap: () {
                                    Get.to(() => SelectTreeTypeDetailsScreen(),
                                        arguments: treeTypeController
                                            .treeTypeList[index]);
                                  },
                                );
                              },
                            ),
                    ),
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

Declare an other list in the controller:

List<TreeType> treeList = [];

And initialise it in your api call:

treeList = tree_types;

And finally update your search function:

void filterTreeTypes(searchString) {
  treeTypeList.value = treeList
    .where((element) =>
        element.name.toLowerCase().contains(searchString.toLowerCase()))
    .toList();
}
  • Related