I am trying to modify the List fetched during the future call and not call the future function again, so assigned a variable to future option of FutureBuilder and called the actual function in the initState(), but now the build function is rendering straight the snapshot.error condition and the build is not even going in the ConnectionState.loading state. Below is the relevant code snippet:
class _BusinessDetailScreenState extends State<BusinessDetailScreen> {
late List<ProductCategory> _uniqueProductCategoryList;
late Future<List<BusinessProduct>> _productsFetch;
@override
void initState() {
super.initState();
_productsFetch = _fetchDetails();
}
List<ProductCategory> fetchUniqueCategory (productList) {
// function body
return List<ProductCategory>.generate(result.length, (index) {
return ProductCategory(
categoryName: result[index]["productCategoryName"],alternateName: result[index]["productCategoryAlternateName"]??= "", id:result[index]["id"]
);
});
}
Future<List<BusinessProduct>> _fetchDetails() async {
var queryParams = {
//params
};
var response = await http.get(Uri.https(Provider.of(context)!.baseUrl,'endpoint',queryParams));
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
List<BusinessProduct> products = jsonResponse.map((e) => BusinessProduct.fromJson(e)).toList();
_uniqueProductCategoryList = fetchUniqueCategory(products);
return products;
}else {
throw Exception('Failed to load Details');
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<dynamic>>(
future: _productsFetch,
builder: (context,snapshot){
print(snapshot); //AsyncSnapshot<List<dynamic>>(ConnectionState.done, null, dependOnInheritedWidgetOfExactType<Provider>() or dependOnInheritedElement() was called before _BusinessDetailScreenState.initState() completed.
if(snapshot.hasData){
return Scaffold(//for data)
} else if(snapshot.hasError){
print(snapshot.error);
// I/flutter ( 4211): dependOnInheritedWidgetOfExactType<Provider>() or dependOnInheritedElement() was called before _BusinessDetailScreenState.initState() completed.
return Scaffold( // for error)
} return Scaffold(
backgroundColor: palletWhite,
body: Center(
child: LoadingComponent(loadingText: 'Fetching data, Please wait',)
)
);
},
);
)
Been stuck on this for a while now, is there anything I'm doing wrong or is there some different approach to this that I should try, please let me know