Line data Source code
1 : // Copyright 2026 The terCAD team. All rights reserved.
2 : // Use of this source code is governed by a CC BY-NC-ND 4.0 license that can be found in the LICENSE file.
3 :
4 : import 'package:app_finance/_classes/herald/app_design.dart';
5 : import 'package:app_finance/_classes/storage/app_preferences.dart';
6 : import 'package:app_finance/_configs/design_type.dart';
7 : import 'package:app_finance/_configs/sorting_type.dart';
8 : import 'package:material_ui/material_ui.dart';
9 : import 'package:provider/provider.dart';
10 :
11 : class AppSorting extends ValueNotifier<AppSortingType> {
12 3 : AppSorting() : super(get());
13 :
14 1 : static AppSortingType get([String? newValue]) {
15 1 : final name = newValue ?? AppPreferences.get(AppPreferences.prefSortingKey);
16 5 : return AppSortingType.values.where((e) => e.name == name).firstOrNull ?? AppSortingType.updatedAtDesc;
17 : }
18 :
19 0 : Future<void> set(String? newValue, [Function? callback]) async {
20 0 : final change = get(newValue);
21 : if (newValue == null) {
22 0 : await AppPreferences.clear(AppPreferences.prefSortingKey);
23 0 : } else if (change != value) {
24 0 : value = change;
25 0 : await AppPreferences.set(AppPreferences.prefSortingKey, newValue);
26 : if (callback != null) {
27 0 : callback();
28 : }
29 : } else {
30 : return;
31 : }
32 0 : notifyListeners();
33 : }
34 :
35 1 : String getKey(BuildContext context) {
36 1 : String? sortingKey = AppPreferences.get(AppPreferences.prefSortingKey);
37 1 : final design = Provider.of<AppDesign>(context, listen: false);
38 : if (sortingKey == null) {
39 2 : if (design.value == AppDesignType.germany) {
40 0 : sortingKey = AppSortingType.titleAsc.name;
41 : } else {
42 1 : sortingKey = AppSortingType.updatedAtDesc.name;
43 : }
44 : }
45 : return sortingKey;
46 : }
47 :
48 1 : int Function(dynamic, dynamic) getSortFunction(BuildContext context) {
49 6 : final sortingKey = AppSortingType.values.where((e) => e.name == getKey(context)).firstOrNull;
50 1 : return (dynamic a, dynamic b) {
51 : switch (sortingKey) {
52 1 : case AppSortingType.amountDesc:
53 0 : return b.details.compareTo(a.details);
54 1 : case AppSortingType.amountAsc:
55 0 : return a.details.compareTo(b.details);
56 1 : case AppSortingType.createdAtDesc:
57 0 : return b.createdAt.compareTo(a.createdAt);
58 1 : case AppSortingType.createdAtAsc:
59 0 : return a.createdAt.compareTo(b.createdAt);
60 1 : case AppSortingType.titleAsc:
61 0 : return a.title.toString().compareTo(b.title.toString());
62 1 : case AppSortingType.titleDesc:
63 0 : return b.title.toString().compareTo(a.title.toString());
64 1 : case AppSortingType.updatedAtDesc:
65 3 : return b.updatedAt.compareTo(a.updatedAt);
66 0 : case AppSortingType.updatedAtAsc:
67 0 : return a.updatedAt.compareTo(b.updatedAt);
68 : default:
69 : return 0;
70 : }
71 : };
72 : }
73 : }
|