import 'package:flutter/cupertino.dart'; import '../../app.dart'; class CategoryApi { static List _categories = []; static List get categories => [..._categories]; static void clearCategories() { _categories.clear(); } static Future> getDescendantCategories(Map params) async { if (_categories.length == 0) { try { const String path = Constants.BASE_URL + 'descendant-categories'; final response = await HttpUtil().get(path: path, queryParameters: params); for (final json in response['data']) { final CategoryModel category = CategoryModel.fromJson(json); _categories.add(category); } return _categories; } catch (error) { debugPrint('CategoryApi get error: $error '); return []; } } return _categories; } static List buildCategoryTree(String newValue) { if (categories.isEmpty) return []; final List list = []; buildTree(newValue, _categories, list); return list; } // build category tree recursively static void buildTree(String searchKey, List sourceList, List destinationList) { for (final category in sourceList) { if (category.name.toLowerCase().contains(searchKey.toLowerCase())) { destinationList.add(category); } else { buildTree(searchKey, category.children, destinationList); } } } }