Files
dragon_ledger/lib/Controller/account_controller.dart

97 lines
2.8 KiB
Dart

import 'dart:async';
import 'package:drift/drift.dart';
import 'package:flutter/material.dart';
import '../Entities/dialog_type_enum.dart';
import '../Entities/drift_database.dart';
import '../Pages/Dialog/dialog_action.dart';
import '../Pages/Dialog/dialog_input_field.dart';
import '../Pages/Dialog/dynamic_dialog.dart';
import '../Repositories/account_repository.dart';
/// Steuert die Interaktion mit den Accounts
class AccountController {
/// Gibt die aktuell gültige Instanz der Klasse zurück
factory AccountController() => _instance;
/// Erstellt eine neue Instanz dieser Klasse
AccountController._internal() {
_newAccountDialog = DynamicDialog(
title: 'Neues Konto erstellen',
icon: Icons.account_balance_wallet,
inputFields: [
const DialogInputField(id: 'name', label: 'Name', autoFocus: true),
],
actions: [
DialogAction(label: 'Abbruch'),
DialogAction(
label: 'Speichern',
isPrimary: true,
onPressed: _saveNewAccount,
),
],
);
_errorNameEmptyDialog = DynamicDialog(
title: 'Fehler!',
icon: Icons.error,
content: const Text('Der Name des Kontos darf nicht leer sein!'),
dialogType: DialogTypeEnum.error,
);
_accountCreatedDialog = DynamicDialog(
title: 'Account erstellt!',
icon: Icons.check_circle,
content: const Text('Das Konto wurde erfolgreich erstellt!'),
dialogType: DialogTypeEnum.success,
);
}
static final AccountController _instance = AccountController._internal();
BuildContext? _buildContext;
final AccountRepository _accountRepository = AccountRepository();
DynamicDialog? _newAccountDialog;
DynamicDialog? _errorNameEmptyDialog;
DynamicDialog? _accountCreatedDialog;
Account? _selected;
/// Stellt das ausgewählte Konto dar, das angezeigt wird
Future<Account?> get selected async => _selected ??= (await getAccounts())[0];
set selected(final Account selected) {
_selected = selected;
}
/// Gibt die gespeicherten Konten als Liste zurück
Future<List<Account>> getAccounts() async {
final List<Account> accounts = await _accountRepository.findBy(
orderBy: 'nameAsc',
);
return accounts;
}
/// Startet den Prozess um ein neues Konto anzulegen
void newAccountHandler(final BuildContext buildContext) {
_buildContext = buildContext;
unawaited(_newAccountDialog?.show(buildContext));
}
Future<void> _saveNewAccount(final Map<String, String> values) async {
if (values['name'] == null || values['name']!.isEmpty) {
if (_buildContext != null) {
await _errorNameEmptyDialog?.show(_buildContext!);
}
} else {
final account = AccountsCompanion(name: Value(values['name']!));
await _accountRepository.add(account);
await _accountCreatedDialog?.show(_buildContext!);
}
}
}