create project
This commit is contained in:
45
frontend/lib/providers/bill_provider.dart
Normal file
45
frontend/lib/providers/bill_provider.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
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));
|
||||
});
|
||||
Reference in New Issue
Block a user