'Flutter - Read json from local file and search and update UI
I am reading a local json file in a provider
Future<List<ProductModel>> readJsonData() async {
final jsondata = await rootBundle.loadString('jsonData/products.json');
final list = json.decode(jsondata) as List<dynamic>;
var _listOfProducts = list.map((e) => ProductModel.fromJson(e)).toList();
return _listOfProducts;
}
and the search function
void searchProduct(String searchText) {
if (searchText == '') {
return;
}
final products = listProducts.where((product) {
final nameLowerCase = product.name!.toLowerCase();
final searchTextLowerCase = searchText.toLowerCase();
return nameLowerCase.contains(searchTextLowerCase);
}).toList();
_searchString = searchText;
listProducts = products;
notifyListeners();
}
and then rendering it like so:
Consumer<ProductsProvider>(builder: (context, productData, child) {
//print(productData.listProducts.toString());
return FutureBuilder(
future: _productsProvider.readJsonData(),
builder: (context, data) {
/// I BELIEVE THIS IS THE CAUSE WHY THE UI WON'T UPDATE
productData.listProducts = data.data as List<ProductModel>;
return Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: productData.listProducts.length,
itemBuilder: (context, index) => Card(
elevation: 3,
child: ListTile(
title: Text(productData.listProducts[index].name!),
),
),
),
);
});
})
search textfield onChange:
onChanged: (value) {
_productsProvider.searchProduct(value);
},
The search works but the UI doesn't change, the list doesn't get filtered because of the line after the comment (above). How do I deal with this so that I get all the items before search (or when the searchText is empty) and the filtered items(list) when there is a searchText?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
