2023-02-27 07:12:45 +00:00
|
|
|
import 'package:flutter/cupertino.dart';
|
|
|
|
|
import '../../app.dart';
|
|
|
|
|
|
|
|
|
|
class CategoryApi {
|
|
|
|
|
static List<CategoryModel> _categories = [];
|
|
|
|
|
|
|
|
|
|
static List<CategoryModel> get categories => [..._categories];
|
|
|
|
|
|
2023-05-10 04:58:40 +00:00
|
|
|
static void clearCategories() {
|
|
|
|
|
_categories.clear();
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-27 07:12:45 +00:00
|
|
|
static Future<List<CategoryModel>> getDescendantCategories(Map<String, dynamic> 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<CategoryModel> buildCategoryTree(String newValue) {
|
|
|
|
|
if (categories.isEmpty) return [];
|
|
|
|
|
|
|
|
|
|
final List<CategoryModel> list = [];
|
|
|
|
|
|
|
|
|
|
buildTree(newValue, _categories, list);
|
|
|
|
|
|
|
|
|
|
return list;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// build category tree recursively
|
|
|
|
|
static void buildTree(String searchKey, List<CategoryModel> sourceList, List<CategoryModel> destinationList) {
|
|
|
|
|
for (final category in sourceList) {
|
|
|
|
|
if (category.name.toLowerCase().contains(searchKey.toLowerCase())) {
|
|
|
|
|
destinationList.add(category);
|
|
|
|
|
} else {
|
|
|
|
|
buildTree(searchKey, category.children, destinationList);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|