How to create a Filter/Search ListView in Flutter 

How to create a FilterSearch ListView in Flutter 

In this guide, we will discuss how to create a Filter/Search ListView in Flutter. What shall we do today is to show the list of fruit using ListView.builder and use a textfield to search the particular Fruits.  At first, we should know what is ListView in flutter is. For these, we should read the article about Understanding a suite of powerful basic widgets

We will create a function to filter the results and this function will be called when the text field changes (onChanged). For these, we will use most of the Dart methods which are given below.

where(): Returns a new lazy Iterable with all elements that satisfy one or many conditions.

contains(): Used to determine whether a string contains another string (you can try other string methods like startsWith()endsWith(), etc).

toLowerCase(): This string method will convert all characters in this string to lower case so that it doesn’t matter whether the search keyword is uppercase or lowercase.

We will also use a third-party library name substring_highlight to highlight the text when users search on the textfield. So The Next Step is to include the dependency inside the pubspec. yaml which is shown below

dependencies:
  flutter:
    sdk: flutter

  substring_highlight: ^1.0.33

Let’s take an example of how we can implement the Animated Icon in our flutter application.

we will create a new model name Fruit that includes the String of name description and the URL of that class name Fruit and store it into a new file inside the lib folder name fruit_model.dart.

class Fruit {
  String name, desc, url;
  Friut({
    required this.name,
    required this.desc,
    required this.url,
  });
}

Now we will again create a new file name as fruit_data.dart that includes the dummy data.

import 'package:vlogpost/model/student.dart';

List<Friut> friuts= [
  Friut(
      name: 'Apple',
      desc:
          'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the',
      url:
          'assets/apple.jpg'),
  Friut(
      name: 'Banana',
      desc:
          'banana is an elongated, edible fruit - botanically a berry - produced by several kinds of large herbaceous flowering plants in the genus Musa.',
      url:
          'assets/banana.jpg'),
  Friut(
      name: 'Grape',
      desc:
          'The grapefruit (Citrus × paradisi) is a subtropical citrus tree known for its relatively large, sour to semi-sweet, somewhat bitter fruit.',
      url:
          'assets/grape.jpg'),
  Friut(
      name: 'Mango',
      desc:
          'A mango is an edible stone fruit produced by the tropical tree Mangifera indica which is believed to have originated from the region between northwestern ...',
      url:
          'assets/mango.jpg'),
  Friut(
      name: 'Orange',
      desc:
          'An orange is a fruit of various citrus species in the family Rutaceae ); it primarily refers to Citrus × sinensis, which is also called sweet orange',
      url:
          'assets/orange.jpg'),
  Friut(
      name: 'WaterMelon',
      desc:
          'Watermelon is grown in favorable climates from tropical to temperate regions worldwide for its large edible fruit',
      url:
          'assets/watermelon.jpg'),
  Friut(
      name: 'Papaya',
      desc:
          'Papayas grow in tropical climates and are also known as papaws or pawpaws. Their sweet taste, vibrant color, and the wide variety of health benefits they ',
      url:
          'assets/papaya.jpg'),
  Friut(
      name: 'Coconut',
      desc:
          'A coconut is the edible fruit of the coconut palm (Cocos nucifera), a tree of the palm family. ',
      url:
          'assets/coconut.jpg'),
  
];

In the above line of code, I have used the local image name as an assets folder to store the image of fruits. for these, I have taken different fruit images which are shown below.

The Next Step is to include the assets folder inside the pubspec. yaml which is shown below

# To add assets to your application, add an assets section, like this:
  assets:
    - assets/

Now let’s implement the code in the Flutter application.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:substring_highlight/substring_highlight.dart';
import 'package:vlogpost/data/food_data.dart';
import 'package:vlogpost/model/student.dart';

class SearchFilterScreen extends StatefulWidget {
  const SearchFilterScreen({Key? key}) : super(key: key);

  @override
  State<SearchFilterScreen> createState() => _SearchFilterScreenState();
}

class _SearchFilterScreenState extends State<SearchFilterScreen> {
  TextEditingController controller = TextEditingController();

  late List<Fruit> fruitslist;
  List<Fruit> result = [];
  @override
  void initState() {
    fruitslist = fruits;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Search Filter listView '),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10),
            child: CupertinoSearchTextField(
              controller: controller,
              onChanged: (value) {
                final fruitValue = fruits.where((e) {
                  final name = e.name.toLowerCase();
                  final querySearch = value.toLowerCase();
                  final description = e.desc.toLowerCase();
                  return name.contains(querySearch) ||
                      description.contains(querySearch);
                }).toList();
                setState(() {
                  fruitslist = fruitValue;
                });
              },
            ),
          ),
          Expanded(
            child: fruitslist.isEmpty
                ? const Center(
                    child: Text(
                    'No Fruit Found',
                    textScaleFactor: 2,
                  ))
                : ListView.builder(
                    shrinkWrap: true,
                    itemCount: fruitslist.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        leading: CircleAvatar(
                          radius: 30,
                          backgroundImage: AssetImage(fruitslist[index].url),
                        ),
                        title: SubstringHighlight(
                          textStyleHighlight: const TextStyle(
                            color: Colors.black,
                            backgroundColor: Color(0xfff7c46c),
                          ),
                          text: fruitslist[index].name,
                          term: controller.text,
                          textStyle: const TextStyle(
                              fontWeight: FontWeight.w600,
                              color: Colors.black,
                              letterSpacing: 0.41,
                              height: 1.3,
                              fontSize: 20),
                        ),
                        subtitle: Text(
                          fruitslist[index].desc,
                          maxLines: 1,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      );
                    }),
          ),
        ],
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thank you for reading the Guide about How to create a Filter/Search ListView in Flutter.

Tags: