create project
This commit is contained in:
52
frontend/lib/providers/family_provider.dart
Normal file
52
frontend/lib/providers/family_provider.dart
Normal file
@@ -0,0 +1,52 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../api/family_api.dart';
|
||||
import '../api/api_client.dart';
|
||||
import '../models/family.dart';
|
||||
|
||||
final familyApiProvider = Provider<FamilyApi>((ref) {
|
||||
return FamilyApi(ref.read(apiClientProvider));
|
||||
});
|
||||
|
||||
class FamilyNotifier extends StateNotifier<AsyncValue<List<Family>>> {
|
||||
final FamilyApi _api;
|
||||
|
||||
FamilyNotifier(this._api) : super(const AsyncValue.loading());
|
||||
|
||||
Future<void> loadFamilies() async {
|
||||
state = const AsyncValue.loading();
|
||||
try {
|
||||
final res = await _api.getFamilies();
|
||||
if (res['success'] == true) {
|
||||
state = AsyncValue.data((res['data'] as List).map((e) => Family.fromJson(e)).toList());
|
||||
} else {
|
||||
state = AsyncValue.error(res['error'] ?? '加载失败', StackTrace.current);
|
||||
}
|
||||
} catch (e, st) {
|
||||
state = AsyncValue.error(e.toString(), st);
|
||||
}
|
||||
}
|
||||
|
||||
Future<Family?> createFamily(String name) async {
|
||||
try {
|
||||
final res = await _api.createFamily(name);
|
||||
if (res['success'] == true) {
|
||||
return Family.fromJson(res['data']);
|
||||
}
|
||||
} catch (_) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<Family?> joinFamily(String inviteCode) async {
|
||||
try {
|
||||
final res = await _api.joinFamily(inviteCode);
|
||||
if (res['success'] == true) {
|
||||
return Family.fromJson(res['data']);
|
||||
}
|
||||
} catch (_) {}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
final familyProvider = StateNotifierProvider<FamilyNotifier, AsyncValue<List<Family>>>((ref) {
|
||||
return FamilyNotifier(ref.read(familyApiProvider));
|
||||
});
|
||||
Reference in New Issue
Block a user