i use bloc for state management to fetch data from api
FutureOr<void> fetchAllDrinksList(
GetAllDrinksList event, Emitter<HomeState> emit) async {
await apiRepository.getAllDrinks().then((value) {
emit(state.copyWith(
status: HomeStatus.success,
drinksList: value,
message: 'success',
));
}).onError((error, stackTrace) {
emit(state.copyWith(
status: HomeStatus.failure, message: error.toString()));
});
}
and display to home page, like this
GridView.builder(
physics: NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 40,
mainAxisSpacing: 20,
childAspectRatio: 0.7,
),
shrinkWrap: true,
padding:
EdgeInsets.symmetric(vertical: 30, horizontal: 25),
itemCount: state.tempDrinksList.isEmpty
? state.drinksList.length
: state.tempDrinksList.length,
itemBuilder: (context, index) {
final drink = state.drinksList[index];
final filterDrinks = state.tempDrinksList[index];
if (state.tempDrinksList.isNotEmpty) {
return buildGridContainer(
filterDrinks); //for filter drinks
} else {
return buildGridContainer(drink); //for non-filter
}
},
);
i have rest of code of ui card for display data from drinks List but i got an error for Flutter API fetch code throws "index out of range" i thinks problem is length of state.drinksList but i use print statement to debug item on list but i get data by use state.drinksList[index].name
Thanks!
Accessing elements from
state.drinksListandstate.tempDrinksListusing the same index, which may result in accessing an index that doesn't exist in one of the lists. This can happen if the lengths of the two lists differ or if the indices are not synchronized properly.