elektronika/lib/app/data/apis/category.dart

55 lines
1.5 KiB
Dart

import 'package:flutter/cupertino.dart';
import '../../app.dart';
class CategoryApi {
static List<CategoryModel> _categories = [];
static List<CategoryModel> get categories => [..._categories];
static void clearCategories() {
_categories.clear();
}
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);
}
}
}
}