我有一个简单的小部件,它可以监听记录的当月费用.这是建立与河舱和漂流包在Flutter .我使用的数据模式是提供者&>存储库&>DAO.
然而,由于某些原因,当我在本地数据库中添加或删除与当前月份匹配的交易时(通过查看SQLite表进行验证),小部件不会使用最新的ExpendsTo Date值进行更新.看起来,这条溪流似乎没有发出新的价值.我已经试着调试这个程序很久了,但不知道出了什么问题.
预期行为:
- 交易记录表中的记录被修改(增加或删除)
- ExpensesToDateProvider发出新值
- 重新构建小部件以反映新价值
// Widget to display latest expenseToDate
class DebugExpensesWidget extends ConsumerWidget {
const DebugExpensesWidget({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final expensesAsyncValue =
ref.watch(expensesToDateProvider(budgetDate: DateTime(DateTime.now().year, DateTime.now().month)));
return expensesAsyncValue.when(
data: (data) {
return Text('Expenses to date: $data');
},
loading: () => CircularProgressIndicator(),
error: (error, _) {
return Text('Error: $error');
},
);
}
}
// Provider that watches spentToDate for the month
@riverpod
Stream<double> expensesToDate(ExpensesToDateRef ref, {required DateTime budgetDate}) {
return ref.watch(budgetsRepositoryProvider).getExpensesToDate(budgetDate);
}
// Repository to call the DAO to return total expenses to date based on a given budgetDate
Stream<double> getExpensesToDate(DateTime budgetDate) {
return database.appDatabaseDao.calculateExpensesToDateDao(budgetDate.year, budgetDate.month);
}
// DAO to calculate Total Expenses to date based on a given month and year
Stream<double> calculateExpensesToDateDao(int year, int month) {
final yearStr = year.toString();
final monthStr = month.toString().padLeft(2, '0');
const sql = '''
SELECT SUM(amount) as total
FROM transactions
WHERE is_income = 0
AND strftime('%m', datetime(transaction_date, 'unixepoch')) = ?
AND strftime('%Y', datetime(transaction_date, 'unixepoch')) = ?
''';
return customSelect(sql, variables: [
Variable.withString(monthStr),
Variable.withString(yearStr),
]).watch().map((rows) {
final row = rows.first;
final total = row.read<double?>('total') ?? 0.0;
return total;
});
}