Implementing Searchable List View in Flutter using data from Network.
By: Nishkarsh Makhija
Tags: Search, Json, Flutter, Listview, Network

STEPS

Step 1 : Include necessary dependencies.

To consume HTTP resource we need this library in our project from https://pub.dev/packages/http . Add following lines in your pubspec.yaml file.

dependencies:

http: ^0.12.0+2

Step 2 : Create statefull widget and initialize global variables.

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;

import 'dart:convert';



class SearchListViewExample extends StatefulWidget {

@override

_SearchListViewExampleState createState() => _SearchListViewExampleState();

}



class _SearchListViewExampleState extends State<SearchListViewExample> {



List<String> dogsBreedList = List<String>();

List<String> tempList = List<String>();

bool isLoading = false;

}

See in the above code two packages is imported.

‘package:http/http.dart’ is imported to call HTTP API and ‘dart:convert’ is used to decode JSON.

dogsBreedList is used to display Dog Breeds List in ListView.

tempList is used to filter List.

isLoading is used to indicate whether list is loading or not.

Step 3 : Implement method to call HTTP Api to get data.

API used in this example application is https://dog.ceo/api/breeds/list/all . This api returns JSON data as shown below:

{

"status":"success",

"message":{

"affenpinscher":[],

"african":[],

"airedale":[],

"basenji":[],

"beagle":[],

"bulldog":["boston","english","french"],

"bullterrier":["staffordshire"],

"cairn":[],

"pomeranian":[]

}

}

Below is the method to call HTTP api and fetch JSON data from it.

_fetchDogsBreed() async{

setState(() {

isLoading = true;

}); tempList = List<String>();

final response = await http.get('https://dog.ceo/api/breeds/list/all'); if(response.statusCode == 200){

final jsonResponse = jsonDecode(response.body);

jsonResponse['message'].forEach((breed,subbreed){

tempList.add(breed.toString().toUpperCase());

});

}

else{

throw Exception("Failed to load Dogs Breeds.");

}

setState(() {

dogsBreedList = tempList;

isLoading = false;

});

}

Step 4 : ListView to display data.

Widget _mainData(){

return Center(

child: isLoading?

CircularProgressIndicator():

ListView.builder(

itemCount: dogsBreedList.length,

itemBuilder: (context,index){

return ListTile(

title: Text(dogsBreedList[index],)

);

}),

);

}

Step 5 : Creating SearchBar.

Widget _searchBar(){

return Container(

padding: EdgeInsets.only(bottom: 16.0),

child: TextField(

decoration: InputDecoration(

hintText: "Search Dog Breeds Here...",

prefixIcon: Icon(Icons.search),

),

onChanged: (text){

_filterDogList(text);

},

),

);

}

Step 6 : Implementing search logic.

_filterDogList(String text) {

if(text.isEmpty){

setState(() {

dogsBreedList = tempList;

});

}

else{

final List<String> filteredBreeds = List<String>();

tempList.map((breed){

if(breed.contains(text.toString().toUpperCase())){

filteredBreeds.add(breed);

}

}).toList();

setState(() {

dogsBreedList = filteredBreeds;

});

}

}

Step 7 : Adding all the widgets to build method.

@override

Widget build(BuildContext context) {

return Padding(

padding: EdgeInsets.all(8.0),

child: Container(

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,

children: <Widget>[

_searchBar(),

Expanded(

flex: 1,

child: _mainData(),

)

],

),

)

);

}

Step 8 : Final Step is to call _fetchDogsBreed() method.

We will call _fetchDogsBreed() in initState() method so that it is called only once.

@override

void initState() {

// TODO: implement initState

super.initState();

_fetchDogsBreed();

}

Now we have implemented the nice ListView using data from internet which is searchable also.