45 lines
1.3 KiB
Dart
45 lines
1.3 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import '../api/bill_api.dart';
|
|
import '../api/api_client.dart';
|
|
import '../models/bill.dart';
|
|
|
|
final billApiProvider = Provider<BillApi>((ref) {
|
|
return BillApi(ref.read(apiClientProvider));
|
|
});
|
|
|
|
class BillNotifier extends StateNotifier<AsyncValue<List<Bill>>> {
|
|
final BillApi _api;
|
|
String? _currentFamilyId;
|
|
|
|
BillNotifier(this._api) : super(const AsyncValue.data([]));
|
|
|
|
Future<void> loadBills({String? familyId}) async {
|
|
_currentFamilyId = familyId;
|
|
state = const AsyncValue.loading();
|
|
try {
|
|
final res = await _api.getBills(familyId: familyId);
|
|
if (res['success'] == true) {
|
|
state = AsyncValue.data((res['data'] as List).map((e) => Bill.fromJson(e)).toList());
|
|
} else {
|
|
state = AsyncValue.error(res['error'] ?? '加载失败', StackTrace.current);
|
|
}
|
|
} catch (e, st) {
|
|
state = AsyncValue.error(e.toString(), st);
|
|
}
|
|
}
|
|
|
|
Future<bool> addBill(Map<String, dynamic> data) async {
|
|
try {
|
|
final res = await _api.createBill(data);
|
|
if (res['success'] == true) {
|
|
await loadBills(familyId: _currentFamilyId);
|
|
return true;
|
|
}
|
|
} catch (_) {}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
final billProvider = StateNotifierProvider<BillNotifier, AsyncValue<List<Bill>>>((ref) {
|
|
return BillNotifier(ref.read(billApiProvider));
|
|
}); |