Files
Aq-Accounting-Flutter/lib/api/category_api.dart
T
2026-09-21 17:37:53 +08:00

35 lines
1.1 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/network/api_exception.dart';
import '../core/network/dio_client.dart';
import '../models/category.dart';
final categoryApiProvider = Provider<CategoryApi>((ref) => CategoryApi(ref.watch(dioProvider)));
class CategoryApi {
final Dio _dio;
CategoryApi(this._dio);
/// 获取分类列表,type: 1=支出 2=收入(后端可能返回裸数组或 {code,data})
Future<List<Category>> getCategories(int type) async {
try {
final res = await _dio.get('/categories', queryParameters: {'type': type});
return _parseList(res.data)
.whereType<Map<String, dynamic>>()
.map(Category.fromJson)
.toList();
} on DioException catch (e) {
final err = e.error;
throw err is ApiException ? err : ApiException(-1, '请求失败');
}
}
List<dynamic> _parseList(Object? data) {
if (data is List) return data;
if (data is Map && data['data'] is List) return data['data'] as List;
throw ApiException(-1, '分类响应格式异常');
}
}