Search Widget using future<List> from JSON Data

Hi there,
I am trying to use the search widget and pull the data from a json source(see below)
The error i am getting at the moment is:
“The argument type ‘Future<List>’ can’t be assigned to the parameter type ‘List’.”

Here is some of my search widget code and also my future code…what have i done wrong and how do i fix it. Thanks

//SEARCH WIDGET CODE
SearchWidget(
dataList: getSearchTerms(), //GO GET DATA
hideSearchBoxWhenItemSelected: false,
listContainerHeight: MediaQuery.of(context).size.height / 4,
queryBuilder: (query, list) {
return list
.where((item) => item.searchterm
.toLowerCase()
.contains(query.toLowerCase()))
.toList();
},
//MORE CODE ETC

//Code to get the search terms
Future<List> getSearchTerms() async {
//URL TO JSON DATA
String url = _baseURL +’/search/getsearchterms.php’;
//Send Request
List searchterms = [];
var response = await http.get(url);
//Check to make sure data is returned ok.
if (response.statusCode == 200) {
if (response.body ==’{“message”:“Something went wrong, please contact IT Support. error code:2”}’){
return throw Exception(‘Error’);
}else{
//Send Data to post to format.
var jsonData = json.decode(response.body);
for (var st in jsonData){
SearchList searchterm = SearchList(st[“searchterm”]);
searchterms.add(searchterm);
}
}
}
return searchterms;
}

class SearchList {
final String searchterm;
SearchList(this.searchterm);
}

//JSON DATA
[
{ searchterm: “council”},
{ searchterm: “CAS”},
{searchterm: “citizen”},
{searchterm: “Citizens Advice Bureau”},
{ searchterm: “help”}
]

Going through your code snippet and SearchWidget class definition, this is what I could understand.

1. Type of dataList property is final List<T>.
2. Return type of getSearchTerms() is Future<List>.

dataList: searchterms
Since there is a mismatch of type you are getting the error:
“The argument type ‘Future’ can’t be assigned to the parameter type ‘List’.”

Given that getSearchTerms is a async function.

I can suggest two options.

First option:
Declare List searchterms = []; at the top most scope, start of the class.
set dataList: searchterms.
Inside getSearchTerms() function, after adding elements to searchterms, call setState.
This will trigger the build function and SearchWidget is built with populated searchterms.

Second option:
A much cleaner approach.
Use Future builder. Only after the server has responded build the SearchWidget.

1 Like