cake_wallet/cw_nano/lib/nano_account_list.dart

70 lines
1.7 KiB
Dart
Raw Normal View History

2023-08-15 19:05:38 +00:00
import 'package:cw_core/cake_hive.dart';
2023-08-10 22:34:20 +00:00
import 'package:cw_core/nano_account.dart';
2023-07-24 20:23:09 +00:00
import 'package:mobx/mobx.dart';
2023-08-10 22:34:20 +00:00
import 'package:hive/hive.dart';
2023-07-24 20:23:09 +00:00
part 'nano_account_list.g.dart';
class NanoAccountList = NanoAccountListBase with _$NanoAccountList;
abstract class NanoAccountListBase with Store {
2023-08-10 22:34:20 +00:00
NanoAccountListBase(this.address)
: accounts = ObservableList<NanoAccount>(),
2023-07-24 20:23:09 +00:00
_isRefreshing = false,
_isUpdating = false {
2023-08-10 22:34:20 +00:00
refresh();
2023-07-24 20:23:09 +00:00
}
@observable
2023-08-10 22:34:20 +00:00
ObservableList<NanoAccount> accounts;
2023-07-24 20:23:09 +00:00
bool _isRefreshing;
bool _isUpdating;
2023-08-10 22:34:20 +00:00
String address;
2023-08-10 23:29:51 +00:00
Future<void> update(String? address) async {
2023-07-24 20:23:09 +00:00
if (_isUpdating) {
return;
}
try {
_isUpdating = true;
2023-08-10 23:29:51 +00:00
final accounts = await getAll(address: address ?? this.address);
2023-07-24 20:23:09 +00:00
if (accounts.isNotEmpty) {
this.accounts.clear();
this.accounts.addAll(accounts);
}
_isUpdating = false;
} catch (e) {
_isUpdating = false;
rethrow;
}
}
2023-08-10 23:29:51 +00:00
Future<List<NanoAccount>> getAll({String? address}) async {
2023-08-15 19:05:38 +00:00
final box = await CakeHive.openBox<NanoAccount>(address ?? this.address);
2023-07-24 20:23:09 +00:00
2023-08-10 22:34:20 +00:00
// get all accounts in box:
return box.values.toList();
}
2023-07-24 20:23:09 +00:00
Future<void> addAccount({required String label}) async {
2023-08-15 19:05:38 +00:00
final box = await CakeHive.openBox<NanoAccount>(address);
2023-08-10 22:34:20 +00:00
final account = NanoAccount(id: box.length, label: label, balance: "0.00", isSelected: false);
await box.add(account);
await account.save();
2023-07-24 20:23:09 +00:00
}
Future<void> setLabelAccount({required int accountIndex, required String label}) async {
2023-08-15 19:05:38 +00:00
final box = await CakeHive.openBox<NanoAccount>(address);
2023-08-10 22:34:20 +00:00
final account = box.getAt(accountIndex);
account!.label = label;
await account.save();
2023-07-24 20:23:09 +00:00
}
2023-08-10 22:34:20 +00:00
void refresh() {}
2023-07-24 20:23:09 +00:00
}