Search code examples
jsonfluttersearchbar

how do i add a search bar for a listview.Builder with a json file?


in my application Flutter I have a widget with this body

body: ListView.builder(
        itemCount: data.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: <Widget>[
              ListTile(
                title: Text(data[index]['name']),
                leading: Icon(Icons.arrow_forward_ios),
                onTap: () => {
                  Navigator.pushNamed(context, data[index]['routes'])
                  // Your Logout method
                },
                //title: Text(data[index]['name']),
              )
            ],
          );
        },
      ),

the variable data depends on a local json file. The json file is like this:

[
    {
        "name" : "name",
        "routes" : "/routes1"
    },
    {
        "name" : "name2",
        "routes" :  "/routes2"
    },
]

For update json file I use this code

Future<String> loadJsonData() async {
    var jsonText =
        await rootBundle.loadString('assets/file.json');
    setState(() {
      data = json.decode(jsonText);
    });
    print(jsonText);
  }

  @override
  // ignore: must_call_super
  void initState() {
    this.loadJsonData();
  }

with this code I have a list that makes me see the name and through 'routes' sends me to another page.

I need to add a search bar, which allows me as I type a name to display only similar ones. For example if the list names in the json file are: Martin Mike James

When I start typing 'M' I will see a list with Martin Mike.

Any suggestions?

Thanks


Solution

  • Since the list is local and will not change. The search can be achieved by using a simple stateful widget.

    The most simple way would be to add a variable in state for filter names and set state with filter names based on the search text. Here I have used a string item please use a class that fits your need.

    allNames variable contains all the names.

    searchedNames variable contains all the names.

    _searchChanged function setsState with searchedName based on test entered in TextField

    // Widget for searching through a string list.
    class SearchNameWidget extends StatefulWidget {
      SearchNameWidget({Key key}) : super(key: key);
    
      @override
      _SearchNameState createState() => _SearchNameState();
    }
    
    class _SearchNameState extends State<SearchNameWidget> {
      // All names
      List<String> allNames = [
        'one',
        'two',
        'three',
        'four',
        'five',
        'six',
        'seven',
        'eight',
        'nine',
        'ten'
      ];
    
      // searched names
      List<String> searchedNames = [
        'one',
        'two',
        'three',
        'four',
        'five',
        'six',
        'seven',
        'eight',
        'nine',
        'ten'
      ];
    
      // changes the filtered name based on search text and sets state.
      void _searchChanged(String searchText) {
        if (searchText != null && searchText.isNotEmpty) {
          setState(() {
            searchedNames =
                List.from(allNames.where((name) => name.contains(searchText)));
          });
        }
        else {
          setState(() {
            searchedNames =
                List.from(allNames);
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Demos'),
          ),
          body: Column(
            children: [
              TextField(
                // calls the _searchChanged on textChange
                onChanged: (search) => _searchChanged(search),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: searchedNames.length,
                  itemBuilder: (context, index) => Container(
                    padding: EdgeInsets.all(5),
                    child: Text(searchedNames[index]),
                  ),
                ),
              ),
            ],
          ),
        );
      }
    }