Skip to content

Commit

Permalink
Merge pull request #35 from liplum-dev/riverpod
Browse files Browse the repository at this point in the history
Riverpod
  • Loading branch information
liplum authored Mar 28, 2024
2 parents 8270b48 + 37fb176 commit 60a1ee3
Show file tree
Hide file tree
Showing 36 changed files with 286 additions and 293 deletions.
2 changes: 1 addition & 1 deletion lib/credentials/init.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class CredentialsInit {
static late CredentialStorage storage;

static void init() {
storage = const CredentialStorage();
storage = CredentialStorage();
Editor.registerEditor<Credentials>((ctx, desc, initial) => StringsEditor(
fields: [
(name: "account", initial: initial.account),
Expand Down
4 changes: 3 additions & 1 deletion lib/credentials/storage/credential.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class _LibraryK {
class CredentialStorage {
Box get box => HiveInit.credentials;

const CredentialStorage();
CredentialStorage();

// OA
Credentials? get oaCredentials => box.safeGet(_OaK.credentials);
Expand Down Expand Up @@ -71,4 +71,6 @@ class CredentialStorage {
ValueListenable<Box> listenLibraryChange() => box.listenable(keys: [
_LibraryK.credentials,
]);

late final $libraryCredentials = box.provider<Credentials>(_LibraryK.credentials);
}
8 changes: 8 additions & 0 deletions lib/life/electricity/aggregated.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,12 @@ class ElectricityAggregated {
ElectricityBalanceInit.storage.lastUpdateTime = null;
ElectricityBalanceInit.storage.lastBalance = null;
}

static Future<void> refresh({required String selectedRoom}) async {
final lastBalance = await ElectricityBalanceInit.service.getBalance(selectedRoom);
if (lastBalance.roomNumber == selectedRoom) {
ElectricityBalanceInit.storage.lastBalance = lastBalance;
ElectricityBalanceInit.storage.lastUpdateTime = DateTime.now();
}
}
}
36 changes: 12 additions & 24 deletions lib/life/electricity/index.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart' hide isCupertino;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:sit/design/adaptive/multiplatform.dart';
import 'package:sit/design/widgets/app.dart';
import 'package:sit/design/adaptive/dialog.dart';
Expand All @@ -20,25 +22,19 @@ import 'init.dart';
import 'widget/card.dart';
import 'widget/search.dart';

class ElectricityBalanceAppCard extends StatefulWidget {
class ElectricityBalanceAppCard extends ConsumerStatefulWidget {
const ElectricityBalanceAppCard({super.key});

@override
State<ElectricityBalanceAppCard> createState() => _ElectricityBalanceAppCardState();
ConsumerState<ElectricityBalanceAppCard> createState() => _ElectricityBalanceAppCardState();
}

class _ElectricityBalanceAppCardState extends State<ElectricityBalanceAppCard> {
final $roomBalance = ElectricityBalanceInit.storage.listenBalance();
final $lastUpdateTime = ElectricityBalanceInit.storage.listenLastUpdateTime();
final $room = Settings.life.electricity.listenSelectedRoom();
class _ElectricityBalanceAppCardState extends ConsumerState<ElectricityBalanceAppCard> {
late final EventSubscription $refreshEvent;

@override
initState() {
super.initState();
$roomBalance.addListener(updateRoomAndBalance);
$lastUpdateTime.addListener(updateRoomAndBalance);
$room.addListener(updateRoomAndBalance);
$refreshEvent = lifeEventBus.addListener(() async {
await refresh(active: true);
});
Expand All @@ -49,27 +45,18 @@ class _ElectricityBalanceAppCardState extends State<ElectricityBalanceAppCard> {

@override
dispose() {
$roomBalance.removeListener(updateRoomAndBalance);
$lastUpdateTime.removeListener(updateRoomAndBalance);
$room.removeListener(updateRoomAndBalance);
$refreshEvent.cancel();
super.dispose();
}

void updateRoomAndBalance() {
setState(() {});
}

/// The electricity balance is refreshed approximately every 15 minutes.
Future<void> refresh({required bool active}) async {
final selectedRoom = Settings.life.electricity.selectedRoom;
if (selectedRoom == null) return;
try {
final lastBalance = await ElectricityBalanceInit.service.getBalance(selectedRoom);
if (lastBalance.roomNumber == selectedRoom) {
ElectricityBalanceInit.storage.lastBalance = lastBalance;
ElectricityBalanceInit.storage.lastUpdateTime = DateTime.now();
}
await ElectricityAggregated.refresh(
selectedRoom: selectedRoom,
);
} catch (error) {
if (active) {
if (!mounted) return;
Expand All @@ -85,9 +72,10 @@ class _ElectricityBalanceAppCardState extends State<ElectricityBalanceAppCard> {

@override
Widget build(BuildContext context) {
final selectedRoom = Settings.life.electricity.selectedRoom;
final lastUpdateTime = ElectricityBalanceInit.storage.lastUpdateTime;
final lastBalance = ElectricityBalanceInit.storage.lastBalance;
final storage = ElectricityBalanceInit.storage;
final lastBalance = ref.watch(storage.$lastBalance);
final selectedRoom = ref.watch(Settings.life.electricity.$selectedRoom);
final lastUpdateTime = ref.watch(storage.$lastUpdateTime);
final balance = lastBalance?.roomNumber == selectedRoom ? lastBalance : null;
final roomNumber = balance != null
? "#${balance.roomNumber}"
Expand Down
2 changes: 1 addition & 1 deletion lib/life/electricity/init.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ class ElectricityBalanceInit {

static void init() {
service = Dev.demoMode ? const DemoElectricityService() : const ElectricityService();
storage = const ElectricityStorage();
storage = ElectricityStorage();
}
}
6 changes: 5 additions & 1 deletion lib/life/electricity/storage/electricity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ class ElectricityStorage {
Box get box => HiveInit.electricity;
final int maxHistoryLength;

const ElectricityStorage({
ElectricityStorage({
this.maxHistoryLength = 20,
});

ValueListenable listenBalance() => box.listenable(keys: [_K.lastBalance]);

late final $lastBalance = box.provider<ElectricityBalance>(_K.lastBalance);

ElectricityBalance? get lastBalance => box.safeGet(_K.lastBalance);

set lastBalance(ElectricityBalance? newV) => box.safePut(_K.lastBalance, newV);
Expand All @@ -40,5 +42,7 @@ class ElectricityStorage {

set lastUpdateTime(DateTime? newV) => box.safePut(_K.lastUpdateTime, newV);

late final $lastUpdateTime = box.provider<DateTime>(_K.lastUpdateTime);

ValueListenable listenLastUpdateTime() => box.listenable(keys: [_K.lastUpdateTime]);
}
4 changes: 2 additions & 2 deletions lib/life/expense_records/aggregated.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ class ExpenseAggregated {
final latestValidBalance = _findLatestValidBalanceTransaction(newlyFetched, newTsList);
// check if the transaction is kept for topping up
if (latestValidBalance != null) {
storage.latestTransaction = latest.copyWith(
storage.lastTransaction = latest.copyWith(
balanceBefore: latestValidBalance.balanceBefore,
balanceAfter: latestValidBalance.balanceAfter,
);
} else {
storage.latestTransaction = latest;
storage.lastTransaction = latest;
}
}
}
Expand Down
18 changes: 7 additions & 11 deletions lib/life/expense_records/index.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:sit/credentials/widgets/oa_scope.dart';
import 'package:sit/design/widgets/app.dart';
Expand All @@ -17,22 +18,18 @@ import 'package:rettulf/rettulf.dart';
import "i18n.dart";
import 'widget/transaction.dart';

class ExpenseRecordsAppCard extends StatefulWidget {
class ExpenseRecordsAppCard extends ConsumerStatefulWidget {
const ExpenseRecordsAppCard({super.key});

@override
State<ExpenseRecordsAppCard> createState() => _ExpenseRecordsAppCardState();
ConsumerState<ExpenseRecordsAppCard> createState() => _ExpenseRecordsAppCardState();
}

class _ExpenseRecordsAppCardState extends State<ExpenseRecordsAppCard> {
final $lastTransaction = ExpenseRecordsInit.storage.listenLastTransaction();
final $lastUpdateTime = ExpenseRecordsInit.storage.listenLastUpdateTime();
class _ExpenseRecordsAppCardState extends ConsumerState<ExpenseRecordsAppCard> {
late final EventSubscription $refreshEvent;

@override
void initState() {
$lastTransaction.addListener(onLatestChanged);
$lastUpdateTime.addListener(onLatestChanged);
$refreshEvent = lifeEventBus.addListener(() async {
await refresh(active: true);
});
Expand All @@ -49,8 +46,6 @@ class _ExpenseRecordsAppCardState extends State<ExpenseRecordsAppCard> {

@override
void dispose() {
$lastTransaction.removeListener(onLatestChanged);
$lastUpdateTime.removeListener(onLatestChanged);
$refreshEvent.cancel();
super.dispose();
}
Expand Down Expand Up @@ -81,8 +76,9 @@ class _ExpenseRecordsAppCardState extends State<ExpenseRecordsAppCard> {

@override
Widget build(BuildContext context) {
final lastTransaction = ExpenseRecordsInit.storage.latestTransaction;
final lastUpdateTime = ExpenseRecordsInit.storage.lastUpdateTime;
final storage = ExpenseRecordsInit.storage;
final lastUpdateTime = ref.watch(storage.$lastUpdateTime);
final lastTransaction = ref.watch(storage.$lastTransaction);
return AppCard(
view: lastTransaction == null
? const SizedBox()
Expand Down
2 changes: 1 addition & 1 deletion lib/life/expense_records/init.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ class ExpenseRecordsInit {

static void init() {
service = Dev.demoMode ? const DemoExpenseService() : const ExpenseService();
storage = const ExpenseStorage();
storage = ExpenseStorage();
}
}
2 changes: 1 addition & 1 deletion lib/life/expense_records/page/records.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class _ExpenseRecordsPageState extends State<ExpenseRecordsPage> {
@override
Widget build(BuildContext context) {
final month2records = this.month2records;
final lastTransaction = ExpenseRecordsInit.storage.latestTransaction;
final lastTransaction = ExpenseRecordsInit.storage.lastTransaction;
return Scaffold(
appBar: AppBar(
title: lastTransaction == null
Expand Down
18 changes: 11 additions & 7 deletions lib/life/expense_records/storage/local.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ class _K {
}

// Don't use lastFetchedTs, and just fetch all translations
static const lastFetchedTs = "/lastFetchedTs";
static const latestTransaction = "/latestTransaction";
// static const lastFetchedTs = "/lastFetchedTs";
static const lastTransaction = "/lastTransaction";
static const lastUpdateTime = "/lastUpdateTime";
}

class ExpenseStorage {
Box get box => HiveInit.expense;

const ExpenseStorage();
ExpenseStorage();

/// 所有交易记录的索引,记录所有的交易时间,需要保证有序,以实现二分查找
List<DateTime>? get transactionTsList => (box.safeGet(_K.transactionTsList) as List?)?.cast<DateTime>();
Expand All @@ -36,23 +36,27 @@ class ExpenseStorage {

setTransactionByTs(DateTime ts, Transaction? transaction) => box.safePut(_K.transaction(ts), transaction);

Transaction? get latestTransaction => box.safeGet(_K.latestTransaction);
Transaction? get lastTransaction => box.safeGet(_K.lastTransaction);

set latestTransaction(Transaction? v) => box.safePut(_K.latestTransaction, v);
set lastTransaction(Transaction? v) => box.safePut(_K.lastTransaction, v);

ValueListenable<Box> listenLastTransaction() => box.listenable(keys: [_K.latestTransaction]);
late final $lastTransaction = box.provider<Transaction>(_K.lastTransaction);

ValueListenable<Box> listenLastTransaction() => box.listenable(keys: [_K.lastTransaction]);

DateTime? get lastUpdateTime => box.safeGet(_K.lastUpdateTime);

set lastUpdateTime(DateTime? newV) => box.safePut(_K.lastUpdateTime, newV);

late final $lastUpdateTime = box.provider<DateTime>(_K.lastUpdateTime);

ValueListenable listenLastUpdateTime() => box.listenable(keys: [_K.lastUpdateTime]);
}

extension ExpenseStorageX on ExpenseStorage {
void clearIndex() {
transactionTsList = null;
latestTransaction = null;
lastTransaction = null;
}

/// Gets the transaction timestamps in range of start to end.
Expand Down
4 changes: 3 additions & 1 deletion lib/life/settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,16 @@ class _ElectricityK {
class _Electricity {
final Box box;

const _Electricity(this.box);
_Electricity(this.box);

bool get autoRefresh => box.safeGet(_ElectricityK.autoRefresh) ?? _kElectricityAutoRefresh;

set autoRefresh(bool foo) => box.safePut(_ElectricityK.autoRefresh, foo);

String? get selectedRoom => box.safeGet(_ElectricityK.selectedRoom);

late final $selectedRoom = box.provider<String>(_ElectricityK.selectedRoom);

set selectedRoom(String? newV) => box.safePut(_ElectricityK.selectedRoom, newV);

ValueListenable listenSelectedRoom() => box.listenable(keys: [_ElectricityK.selectedRoom]);
Expand Down
39 changes: 16 additions & 23 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sit/files.dart';
Expand Down Expand Up @@ -96,36 +97,28 @@ void main() async {
await Init.initNetwork();
await Init.initModules();
runApp(
const MimirApp().withEasyLocalization().withScreenUtils(),
);
}

final _yamlAssetsLoader = YamlAssetLoader();

extension _AppX on Widget {
Widget withEasyLocalization() {
return EasyLocalization(
EasyLocalization(
supportedLocales: R.supportedLocales,
path: 'assets/l10n',
fallbackLocale: R.defaultLocale,
useFallbackTranslations: true,
assetLoader: _yamlAssetsLoader,
child: this,
);
}

Widget withScreenUtils() {
return ScreenUtilInit(
designSize: const Size(360, 690),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) {
return this;
},
);
}
child: ScreenUtilInit(
designSize: const Size(360, 690),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) {
return const ProviderScope(
child: MimirApp(),
);
},
),
),
);
}

final _yamlAssetsLoader = YamlAssetLoader();

Future<List<String>> _loadRoomNumberList() async {
String jsonData = await rootBundle.loadString("assets/room_list.json");
List<dynamic> list = jsonDecode(jsonData);
Expand Down
Loading

0 comments on commit 60a1ee3

Please sign in to comment.