32 lines
1.1 KiB
Dart
32 lines
1.1 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
|
|
import '../api/account_api.dart';
|
|
import '../core/network/api_exception.dart';
|
|
import '../models/account.dart';
|
|
|
|
/// 账户信息(余额 / 总收入 / 总支出)
|
|
class AccountNotifier extends AsyncNotifier<AccountInfo> {
|
|
@override
|
|
Future<AccountInfo> build() => ref.watch(accountApiProvider).getAccount();
|
|
|
|
/// 把账户余额改成 [targetBalance]。
|
|
///
|
|
/// 后端只能写期初余额,所以这里先反算:
|
|
/// `initialBalance = targetBalance - totalIncome + totalExpense`
|
|
Future<void> setBalance(double targetBalance) async {
|
|
final current = state.value;
|
|
if (current == null) throw ApiException(-1, '账户信息尚未加载完成');
|
|
|
|
final initial = initialBalanceFor(
|
|
targetBalance: targetBalance,
|
|
totalIncome: current.totalIncome,
|
|
totalExpense: current.totalExpense,
|
|
);
|
|
final updated = await ref.read(accountApiProvider).updateBalance(initial);
|
|
state = AsyncData(updated);
|
|
}
|
|
}
|
|
|
|
final accountProvider =
|
|
AsyncNotifierProvider<AccountNotifier, AccountInfo>(AccountNotifier.new);
|