i’m trying to fetch a list of sub categories based on category id, for example:
- Category A has 3 sub categories: A1 – A2 – A3
My backend works fine, I pass the category_id
to the function and it returns me a list of sub categories having the category_id
.
Since i’m new to getx, I tried passing the category_id
as a route parameter but i’m not able to show the list of sub categories. In fact I didn’t get how to pass the category_id
while in the UI.
Here is my repo:
Future<Response> getSubCategoriesListByCategory(int categ_id) async {
return await apiClient.getData('shop/category/$categ_id');
}
Here is my controller:
List<dynamic> _subCategoriesListByCategory = [];
List<dynamic> get subCategoriesListByCategory => _subCategoriesListByCategory;
bool _isLoaded = false;
bool get isLoaded => _isLoaded;
Future<void> getSubCategoriesByCategoryId(int cat_id) async {
Response response =
await subCategoriesRepo.getSubCategoriesListByCategory(cat_id);
if (response.statusCode == 200) {
_subCategoriesListByCategory = [];
_subCategoriesListByCategory.addAll(response.body);
_isLoaded = true;
//print(categoriesList);
update(); // = setState();
} else {}
}
Here is my RouteHelper:
GetPage(
name: subCategory,
page: () {
var catId = Get.parameters['catId'];
return SubCategoriesPage(catId: int.parse(catId!));
},
transition: Transition.fadeIn),
And here is my UI:
GetBuilder<SubCategoriesController>(builder: (subCategories) {
return GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: ScrollPhysics(),
mainAxisSpacing: 16,
crossAxisSpacing: 16,
childAspectRatio: 90 / 100,
padding: EdgeInsets.all(16),
children: List.generate(
subCategories.subCategoriesListByCategory.length, (index) {
return _buildSingleSubCategory(
index,
SubCategoryModel.fromJson(
subCategories.subCategoriesListByCategory[index]));
}),
);
})
Code from home page where i’m passing the category_id:
onTap: () {
Get.toNamed(RouteHelper.getSubCategory(category.id));
},
- I’m able to print the clicked category’s id in the subs page which means it’s passed correctly, also i’m getting
GOING TO ROUTE /sub-category?catId=3
Noting that i’m priting the specific category_id correctly in the sub categories page, I couldn’t fetch the specific data related to them. Any suggestion on how to solve this?
2
Answers
Solved it by adding:
Get.find<SubCategoriesController().getSubCategories(widget.catId);
inside theGetBuilder()
I’m not sure if this helps you since I haven’t seen your full code, but I’m guessing you want to add this as parameter to your
GetBuilder