This commit is contained in:
2026-07-27 21:32:03 +02:00
parent 160b4e4cda
commit 77c1747b40
23 changed files with 1392 additions and 87 deletions
BIN
View File
Binary file not shown.
+35 -7
View File
@@ -1,22 +1,50 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:kooltab2/theme.dart';
import 'package:kooltab2/utils/app_update_util.dart';
class KoolTabApp extends StatelessWidget {
const KoolTabApp({
super.key,
required this.router,
});
class KoolTabApp extends StatefulWidget {
const KoolTabApp({super.key, required this.router});
final GoRouter router;
@override
State<KoolTabApp> createState() => _KoolTabAppState();
}
class _KoolTabAppState extends State<KoolTabApp> {
@override
void initState() {
super.initState();
_checkForUpdates();
}
Future<void> _checkForUpdates() async {
final updater = AppUpdateUtil(serverUrl: "http://localhost:3000/");
try {
final update = await updater.checkForUpdate();
if (update == null) {
return;
}
debugPrint("Update available: ${update.version}");
// TODO:
// Show update dialog here
} catch (e) {
debugPrint("Update check failed: $e");
}
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'KoolTab',
debugShowCheckedModeBanner: false,
routerConfig: router,
// theme: lightTheme,
routerConfig: widget.router,
theme: darkTheme,
);
}
+10
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:kooltab2/views/settings_view.dart';
import '../viewmodels/pin_lock_view_model.dart';
import '../views/bar_screen_view.dart';
@@ -31,6 +32,10 @@ GoRouter createAppRouter(PinLockViewModel pinLockViewModel) {
return null;
},
routes: [
GoRoute(
path: '/',
redirect: (context, state) => '/bar'
),
GoRoute(
path: '/lock',
builder: (context, state) => PinEntryView(
@@ -67,6 +72,11 @@ GoRouter createAppRouter(PinLockViewModel pinLockViewModel) {
path: '/history',
builder: (context, state) => const HistoryScreenView(),
),
GoRoute(
path: '/settings',
builder: (context, state) => const SettingsScreenView(),
),
],
);
}
+20 -1
View File
@@ -93,6 +93,19 @@ class ClosedTabItems extends Table {
Set<Column> get primaryKey => {id};
}
@DataClassName('AppSettingsRow')
class AppSettingsTable extends Table {
@override
String get tableName => 'app_settings';
TextColumn get id => text()();
BoolColumn get pinRequired => boolean().withDefault(const Constant(false))();
TextColumn get themeMode => text().withDefault(const Constant('system'))();
@override
Set<Column> get primaryKey => {id};
}
@DriftDatabase(
tables: [
Products,
@@ -100,7 +113,9 @@ class ClosedTabItems extends Table {
TabItems,
ClosedTabs,
ClosedTabItems
ClosedTabItems,
AppSettingsTable
],
)
class AppDatabase extends _$AppDatabase {
@@ -129,6 +144,10 @@ class AppDatabase extends _$AppDatabase {
await migrator.createTable(closedTabs);
await migrator.createTable(closedTabItems);
}
if (from < 5){
await migrator.createTable(appSettingsTable);
}
},
);
}
+441
View File
@@ -2126,6 +2126,271 @@ class ClosedTabItemsCompanion extends UpdateCompanion<ClosedTabItemRow> {
}
}
class $AppSettingsTableTable extends AppSettingsTable
with TableInfo<$AppSettingsTableTable, AppSettingsRow> {
@override
final GeneratedDatabase attachedDatabase;
final String? _alias;
$AppSettingsTableTable(this.attachedDatabase, [this._alias]);
static const VerificationMeta _idMeta = const VerificationMeta('id');
@override
late final GeneratedColumn<String> id = GeneratedColumn<String>(
'id',
aliasedName,
false,
type: DriftSqlType.string,
requiredDuringInsert: true,
);
static const VerificationMeta _pinRequiredMeta = const VerificationMeta(
'pinRequired',
);
@override
late final GeneratedColumn<bool> pinRequired = GeneratedColumn<bool>(
'pin_required',
aliasedName,
false,
type: DriftSqlType.bool,
requiredDuringInsert: false,
defaultConstraints: GeneratedColumn.constraintIsAlways(
'CHECK ("pin_required" IN (0, 1))',
),
defaultValue: const Constant(false),
);
static const VerificationMeta _themeModeMeta = const VerificationMeta(
'themeMode',
);
@override
late final GeneratedColumn<String> themeMode = GeneratedColumn<String>(
'theme_mode',
aliasedName,
false,
type: DriftSqlType.string,
requiredDuringInsert: false,
defaultValue: const Constant('system'),
);
@override
List<GeneratedColumn> get $columns => [id, pinRequired, themeMode];
@override
String get aliasedName => _alias ?? actualTableName;
@override
String get actualTableName => $name;
static const String $name = 'app_settings';
@override
VerificationContext validateIntegrity(
Insertable<AppSettingsRow> instance, {
bool isInserting = false,
}) {
final context = VerificationContext();
final data = instance.toColumns(true);
if (data.containsKey('id')) {
context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta));
} else if (isInserting) {
context.missing(_idMeta);
}
if (data.containsKey('pin_required')) {
context.handle(
_pinRequiredMeta,
pinRequired.isAcceptableOrUnknown(
data['pin_required']!,
_pinRequiredMeta,
),
);
}
if (data.containsKey('theme_mode')) {
context.handle(
_themeModeMeta,
themeMode.isAcceptableOrUnknown(data['theme_mode']!, _themeModeMeta),
);
}
return context;
}
@override
Set<GeneratedColumn> get $primaryKey => {id};
@override
AppSettingsRow map(Map<String, dynamic> data, {String? tablePrefix}) {
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';
return AppSettingsRow(
id: attachedDatabase.typeMapping.read(
DriftSqlType.string,
data['${effectivePrefix}id'],
)!,
pinRequired: attachedDatabase.typeMapping.read(
DriftSqlType.bool,
data['${effectivePrefix}pin_required'],
)!,
themeMode: attachedDatabase.typeMapping.read(
DriftSqlType.string,
data['${effectivePrefix}theme_mode'],
)!,
);
}
@override
$AppSettingsTableTable createAlias(String alias) {
return $AppSettingsTableTable(attachedDatabase, alias);
}
}
class AppSettingsRow extends DataClass implements Insertable<AppSettingsRow> {
final String id;
final bool pinRequired;
final String themeMode;
const AppSettingsRow({
required this.id,
required this.pinRequired,
required this.themeMode,
});
@override
Map<String, Expression> toColumns(bool nullToAbsent) {
final map = <String, Expression>{};
map['id'] = Variable<String>(id);
map['pin_required'] = Variable<bool>(pinRequired);
map['theme_mode'] = Variable<String>(themeMode);
return map;
}
AppSettingsTableCompanion toCompanion(bool nullToAbsent) {
return AppSettingsTableCompanion(
id: Value(id),
pinRequired: Value(pinRequired),
themeMode: Value(themeMode),
);
}
factory AppSettingsRow.fromJson(
Map<String, dynamic> json, {
ValueSerializer? serializer,
}) {
serializer ??= driftRuntimeOptions.defaultSerializer;
return AppSettingsRow(
id: serializer.fromJson<String>(json['id']),
pinRequired: serializer.fromJson<bool>(json['pinRequired']),
themeMode: serializer.fromJson<String>(json['themeMode']),
);
}
@override
Map<String, dynamic> toJson({ValueSerializer? serializer}) {
serializer ??= driftRuntimeOptions.defaultSerializer;
return <String, dynamic>{
'id': serializer.toJson<String>(id),
'pinRequired': serializer.toJson<bool>(pinRequired),
'themeMode': serializer.toJson<String>(themeMode),
};
}
AppSettingsRow copyWith({String? id, bool? pinRequired, String? themeMode}) =>
AppSettingsRow(
id: id ?? this.id,
pinRequired: pinRequired ?? this.pinRequired,
themeMode: themeMode ?? this.themeMode,
);
AppSettingsRow copyWithCompanion(AppSettingsTableCompanion data) {
return AppSettingsRow(
id: data.id.present ? data.id.value : this.id,
pinRequired: data.pinRequired.present
? data.pinRequired.value
: this.pinRequired,
themeMode: data.themeMode.present ? data.themeMode.value : this.themeMode,
);
}
@override
String toString() {
return (StringBuffer('AppSettingsRow(')
..write('id: $id, ')
..write('pinRequired: $pinRequired, ')
..write('themeMode: $themeMode')
..write(')'))
.toString();
}
@override
int get hashCode => Object.hash(id, pinRequired, themeMode);
@override
bool operator ==(Object other) =>
identical(this, other) ||
(other is AppSettingsRow &&
other.id == this.id &&
other.pinRequired == this.pinRequired &&
other.themeMode == this.themeMode);
}
class AppSettingsTableCompanion extends UpdateCompanion<AppSettingsRow> {
final Value<String> id;
final Value<bool> pinRequired;
final Value<String> themeMode;
final Value<int> rowid;
const AppSettingsTableCompanion({
this.id = const Value.absent(),
this.pinRequired = const Value.absent(),
this.themeMode = const Value.absent(),
this.rowid = const Value.absent(),
});
AppSettingsTableCompanion.insert({
required String id,
this.pinRequired = const Value.absent(),
this.themeMode = const Value.absent(),
this.rowid = const Value.absent(),
}) : id = Value(id);
static Insertable<AppSettingsRow> custom({
Expression<String>? id,
Expression<bool>? pinRequired,
Expression<String>? themeMode,
Expression<int>? rowid,
}) {
return RawValuesInsertable({
if (id != null) 'id': id,
if (pinRequired != null) 'pin_required': pinRequired,
if (themeMode != null) 'theme_mode': themeMode,
if (rowid != null) 'rowid': rowid,
});
}
AppSettingsTableCompanion copyWith({
Value<String>? id,
Value<bool>? pinRequired,
Value<String>? themeMode,
Value<int>? rowid,
}) {
return AppSettingsTableCompanion(
id: id ?? this.id,
pinRequired: pinRequired ?? this.pinRequired,
themeMode: themeMode ?? this.themeMode,
rowid: rowid ?? this.rowid,
);
}
@override
Map<String, Expression> toColumns(bool nullToAbsent) {
final map = <String, Expression>{};
if (id.present) {
map['id'] = Variable<String>(id.value);
}
if (pinRequired.present) {
map['pin_required'] = Variable<bool>(pinRequired.value);
}
if (themeMode.present) {
map['theme_mode'] = Variable<String>(themeMode.value);
}
if (rowid.present) {
map['rowid'] = Variable<int>(rowid.value);
}
return map;
}
@override
String toString() {
return (StringBuffer('AppSettingsTableCompanion(')
..write('id: $id, ')
..write('pinRequired: $pinRequired, ')
..write('themeMode: $themeMode, ')
..write('rowid: $rowid')
..write(')'))
.toString();
}
}
abstract class _$AppDatabase extends GeneratedDatabase {
_$AppDatabase(QueryExecutor e) : super(e);
$AppDatabaseManager get managers => $AppDatabaseManager(this);
@@ -2134,6 +2399,9 @@ abstract class _$AppDatabase extends GeneratedDatabase {
late final $TabItemsTable tabItems = $TabItemsTable(this);
late final $ClosedTabsTable closedTabs = $ClosedTabsTable(this);
late final $ClosedTabItemsTable closedTabItems = $ClosedTabItemsTable(this);
late final $AppSettingsTableTable appSettingsTable = $AppSettingsTableTable(
this,
);
@override
Iterable<TableInfo<Table, Object?>> get allTables =>
allSchemaEntities.whereType<TableInfo<Table, Object?>>();
@@ -2144,6 +2412,7 @@ abstract class _$AppDatabase extends GeneratedDatabase {
tabItems,
closedTabs,
closedTabItems,
appSettingsTable,
];
@override
StreamQueryUpdateRules get streamUpdateRules => const StreamQueryUpdateRules([
@@ -3677,6 +3946,176 @@ typedef $$ClosedTabItemsTableProcessedTableManager =
ClosedTabItemRow,
PrefetchHooks Function()
>;
typedef $$AppSettingsTableTableCreateCompanionBuilder =
AppSettingsTableCompanion Function({
required String id,
Value<bool> pinRequired,
Value<String> themeMode,
Value<int> rowid,
});
typedef $$AppSettingsTableTableUpdateCompanionBuilder =
AppSettingsTableCompanion Function({
Value<String> id,
Value<bool> pinRequired,
Value<String> themeMode,
Value<int> rowid,
});
class $$AppSettingsTableTableFilterComposer
extends Composer<_$AppDatabase, $AppSettingsTableTable> {
$$AppSettingsTableTableFilterComposer({
required super.$db,
required super.$table,
super.joinBuilder,
super.$addJoinBuilderToRootComposer,
super.$removeJoinBuilderFromRootComposer,
});
ColumnFilters<String> get id => $composableBuilder(
column: $table.id,
builder: (column) => ColumnFilters(column),
);
ColumnFilters<bool> get pinRequired => $composableBuilder(
column: $table.pinRequired,
builder: (column) => ColumnFilters(column),
);
ColumnFilters<String> get themeMode => $composableBuilder(
column: $table.themeMode,
builder: (column) => ColumnFilters(column),
);
}
class $$AppSettingsTableTableOrderingComposer
extends Composer<_$AppDatabase, $AppSettingsTableTable> {
$$AppSettingsTableTableOrderingComposer({
required super.$db,
required super.$table,
super.joinBuilder,
super.$addJoinBuilderToRootComposer,
super.$removeJoinBuilderFromRootComposer,
});
ColumnOrderings<String> get id => $composableBuilder(
column: $table.id,
builder: (column) => ColumnOrderings(column),
);
ColumnOrderings<bool> get pinRequired => $composableBuilder(
column: $table.pinRequired,
builder: (column) => ColumnOrderings(column),
);
ColumnOrderings<String> get themeMode => $composableBuilder(
column: $table.themeMode,
builder: (column) => ColumnOrderings(column),
);
}
class $$AppSettingsTableTableAnnotationComposer
extends Composer<_$AppDatabase, $AppSettingsTableTable> {
$$AppSettingsTableTableAnnotationComposer({
required super.$db,
required super.$table,
super.joinBuilder,
super.$addJoinBuilderToRootComposer,
super.$removeJoinBuilderFromRootComposer,
});
GeneratedColumn<String> get id =>
$composableBuilder(column: $table.id, builder: (column) => column);
GeneratedColumn<bool> get pinRequired => $composableBuilder(
column: $table.pinRequired,
builder: (column) => column,
);
GeneratedColumn<String> get themeMode =>
$composableBuilder(column: $table.themeMode, builder: (column) => column);
}
class $$AppSettingsTableTableTableManager
extends
RootTableManager<
_$AppDatabase,
$AppSettingsTableTable,
AppSettingsRow,
$$AppSettingsTableTableFilterComposer,
$$AppSettingsTableTableOrderingComposer,
$$AppSettingsTableTableAnnotationComposer,
$$AppSettingsTableTableCreateCompanionBuilder,
$$AppSettingsTableTableUpdateCompanionBuilder,
(
AppSettingsRow,
BaseReferences<
_$AppDatabase,
$AppSettingsTableTable,
AppSettingsRow
>,
),
AppSettingsRow,
PrefetchHooks Function()
> {
$$AppSettingsTableTableTableManager(
_$AppDatabase db,
$AppSettingsTableTable table,
) : super(
TableManagerState(
db: db,
table: table,
createFilteringComposer: () =>
$$AppSettingsTableTableFilterComposer($db: db, $table: table),
createOrderingComposer: () =>
$$AppSettingsTableTableOrderingComposer($db: db, $table: table),
createComputedFieldComposer: () =>
$$AppSettingsTableTableAnnotationComposer($db: db, $table: table),
updateCompanionCallback:
({
Value<String> id = const Value.absent(),
Value<bool> pinRequired = const Value.absent(),
Value<String> themeMode = const Value.absent(),
Value<int> rowid = const Value.absent(),
}) => AppSettingsTableCompanion(
id: id,
pinRequired: pinRequired,
themeMode: themeMode,
rowid: rowid,
),
createCompanionCallback:
({
required String id,
Value<bool> pinRequired = const Value.absent(),
Value<String> themeMode = const Value.absent(),
Value<int> rowid = const Value.absent(),
}) => AppSettingsTableCompanion.insert(
id: id,
pinRequired: pinRequired,
themeMode: themeMode,
rowid: rowid,
),
withReferenceMapper: (p0) => p0
.map((e) => (e.readTable(table), BaseReferences(db, table, e)))
.toList(),
prefetchHooksCallback: null,
),
);
}
typedef $$AppSettingsTableTableProcessedTableManager =
ProcessedTableManager<
_$AppDatabase,
$AppSettingsTableTable,
AppSettingsRow,
$$AppSettingsTableTableFilterComposer,
$$AppSettingsTableTableOrderingComposer,
$$AppSettingsTableTableAnnotationComposer,
$$AppSettingsTableTableCreateCompanionBuilder,
$$AppSettingsTableTableUpdateCompanionBuilder,
(
AppSettingsRow,
BaseReferences<_$AppDatabase, $AppSettingsTableTable, AppSettingsRow>,
),
AppSettingsRow,
PrefetchHooks Function()
>;
class $AppDatabaseManager {
final _$AppDatabase _db;
@@ -3691,4 +4130,6 @@ class $AppDatabaseManager {
$$ClosedTabsTableTableManager(_db, _db.closedTabs);
$$ClosedTabItemsTableTableManager get closedTabItems =>
$$ClosedTabItemsTableTableManager(_db, _db.closedTabItems);
$$AppSettingsTableTableTableManager get appSettingsTable =>
$$AppSettingsTableTableTableManager(_db, _db.appSettingsTable);
}
+18 -14
View File
@@ -3,8 +3,10 @@ import 'package:flutter/services.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:kooltab2/services/pin_lock_service.dart';
import 'package:kooltab2/services/settings_service.dart';
import 'package:kooltab2/viewmodels/history_view_model.dart';
import 'package:kooltab2/viewmodels/pin_lock_view_model.dart';
import 'package:kooltab2/viewmodels/settings_view_model.dart';
import 'package:provider/provider.dart';
import 'app/app.dart';
@@ -40,14 +42,16 @@ Future<void> main() async {
dispose: (_, database) => database.close(),
),
Provider<ProductService>(
create: (context) => DriftProductService(
database: context.read<AppDatabase>(),
),
create: (context) =>
DriftProductService(database: context.read<AppDatabase>()),
),
Provider<BarTabService>(
create: (context) => DriftBarTabService(
database: context.read<AppDatabase>(),
),
create: (context) =>
DriftBarTabService(database: context.read<AppDatabase>()),
),
Provider<SettingsService>(
create: (context) =>
DriftSettingsService(database: context.read<AppDatabase>()),
),
ChangeNotifierProvider<ProductListViewModel>(
create: (context) => ProductListViewModel(
@@ -55,21 +59,21 @@ Future<void> main() async {
),
),
ChangeNotifierProvider<BarScreenViewModel>(
create: (context) => BarScreenViewModel(
barTabService: context.read<BarTabService>(),
),
create: (context) =>
BarScreenViewModel(barTabService: context.read<BarTabService>(), productService: context.read<ProductService>()),
),
ChangeNotifierProvider<HistoryViewModel>(
create: (context) =>
HistoryViewModel(barTabService: context.read<BarTabService>()),
),
ChangeNotifierProvider<PinLockViewModel>.value(
value: pinLockViewModel,
ChangeNotifierProvider<PinLockViewModel>.value(value: pinLockViewModel),
ChangeNotifierProvider<SettingsViewModel>(
create: (context) => SettingsViewModel(
settingsService: context.read<SettingsService>(),
),
),
],
child: AppBootstrap(
child: KoolTabApp(router: appRouter),
),
child: AppBootstrap(child: KoolTabApp(router: appRouter)),
),
);
}
+26
View File
@@ -0,0 +1,26 @@
enum AppThemeMode { system, light, dark }
class AppSettings {
final bool pinRequired;
final AppThemeMode themeMode;
const AppSettings({
required this.pinRequired,
required this.themeMode,
});
AppSettings copyWith({
bool? pinRequired,
AppThemeMode? themeMode,
}) {
return AppSettings(
pinRequired: pinRequired ?? this.pinRequired,
themeMode: themeMode ?? this.themeMode,
);
}
static const AppSettings defaults = AppSettings(
pinRequired: false,
themeMode: AppThemeMode.system,
);
}
-4
View File
@@ -231,7 +231,6 @@ class DriftBarTabService implements BarTabService {
final items = await _getItemsForTab(tabId);
if (items.isEmpty) {
// Nothing to settle, leave the tab as-is.
return;
}
@@ -263,9 +262,6 @@ class DriftBarTabService implements BarTabService {
..where((item) => item.tabId.equals(tabId));
await deleteQuery.go();
// Note: tab status/customerName untouched on purpose — the tab
// stays open so it keeps showing in the open tabs list.
});
}
+1 -4
View File
@@ -4,12 +4,9 @@ import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Stores and verifies a PIN. The raw PIN is never persisted — only a
/// salted SHA-256 hash of it, kept in secure storage (Keychain on iOS,
/// EncryptedSharedPreferences/Keystore on Android).
class PinLockService {
PinLockService({FlutterSecureStorage? storage})
: _storage = storage ?? const FlutterSecureStorage();
: _storage = storage ?? const FlutterSecureStorage();
static const _saltKey = 'pin_salt';
static const _hashKey = 'pin_hash';
+38
View File
@@ -21,6 +21,9 @@ abstract class ProductService {
Future<void> updateProduct(Product product);
Future<void> deleteProduct(String id);
Future<void> decreaseStock(String productId, int amount);
Future<void> increaseStock(String productId, int amount);
}
class DriftProductService implements ProductService {
@@ -118,4 +121,39 @@ class DriftProductService implements ProductService {
await query.go();
}
@override
Future<void> decreaseStock(String productId, int amount) async {
final product = await getProductById(productId);
if (product == null) {
throw Exception('Product not found');
}
if (product.stockQuantity < amount) {
throw Exception('Not enough stock');
}
await updateProduct(
product.copyWith(
stockQuantity: product.stockQuantity - amount,
),
);
}
@override
Future<void> increaseStock(String productId, int amount) async {
final product = await getProductById(productId);
if (product == null) {
throw Exception('Product not found');
}
await updateProduct(
product.copyWith(
stockQuantity: product.stockQuantity + amount,
),
);
}
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:drift/drift.dart';
import '../database/app_database.dart';
import '../models/settings.dart';
abstract class SettingsService {
Future<AppSettings> getSettings();
Future<void> saveSettings(AppSettings settings);
}
class DriftSettingsService implements SettingsService {
final AppDatabase database;
static const _settingsId = 'app_settings';
DriftSettingsService({required this.database});
AppSettings _mapRowToSettings(AppSettingsRow row) {
return AppSettings(
pinRequired: row.pinRequired,
themeMode: AppThemeMode.values.firstWhere(
(mode) => mode.name == row.themeMode,
orElse: () => AppThemeMode.system,
),
);
}
@override
Future<AppSettings> getSettings() async {
final query = database.select(database.appSettingsTable)
..where((s) => s.id.equals(_settingsId));
final row = await query.getSingleOrNull();
if (row == null) return AppSettings.defaults;
return _mapRowToSettings(row);
}
@override
Future<void> saveSettings(AppSettings settings) async {
await database.into(database.appSettingsTable).insertOnConflictUpdate(
AppSettingsTableCompanion.insert(
id: _settingsId,
pinRequired: Value(settings.pinRequired),
themeMode: Value(settings.themeMode.name),
),
);
}
}
+6 -6
View File
@@ -63,7 +63,7 @@ final ThemeData darkTheme = ThemeData(
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(
backgroundColor: Colors.white.withOpacity(0.05),
backgroundColor: Colors.white.withValues(alpha: 0.05),
foregroundColor: Colors.white70,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppRadii.md),
@@ -90,7 +90,7 @@ final ThemeData darkTheme = ThemeData(
elevation: 0,
backgroundColor: _violet,
foregroundColor: Colors.white,
disabledBackgroundColor: Colors.white.withOpacity(0.06),
disabledBackgroundColor: Colors.white.withValues(alpha: 0.06),
disabledForegroundColor: Colors.white24,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
@@ -195,7 +195,7 @@ final ThemeData darkTheme = ThemeData(
navigationBarTheme: NavigationBarThemeData(
backgroundColor: _surface,
indicatorColor: _violet.withOpacity(0.25),
indicatorColor: _violet.withValues(alpha: 0.25),
labelTextStyle: const WidgetStatePropertyAll(
TextStyle(fontWeight: FontWeight.w600),
),
@@ -484,7 +484,7 @@ final ThemeData lightTheme = ThemeData(
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(
backgroundColor: Colors.black.withOpacity(0.04),
backgroundColor: Colors.black.withValues(alpha: 0.04),
foregroundColor: Colors.black54,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppRadii.md),
@@ -511,7 +511,7 @@ final ThemeData lightTheme = ThemeData(
elevation: 0,
backgroundColor: _violetL,
foregroundColor: Colors.white,
disabledBackgroundColor: Colors.black.withOpacity(0.06),
disabledBackgroundColor: Colors.black.withValues(alpha: 0.06),
disabledForegroundColor: Colors.black26,
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.xl,
@@ -616,7 +616,7 @@ final ThemeData lightTheme = ThemeData(
navigationBarTheme: NavigationBarThemeData(
backgroundColor: _surfaceL,
indicatorColor: _violetL.withOpacity(0.15),
indicatorColor: _violetL.withValues(alpha: 0.15),
labelTextStyle: const WidgetStatePropertyAll(
TextStyle(fontWeight: FontWeight.w600),
),
+242
View File
@@ -0,0 +1,242 @@
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;
// import 'package:open_filex/open_filex.dart';
// import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
class UpdateInfo {
final bool update;
final String version;
final String notes;
final bool mandatory;
final String sha256;
final String download;
UpdateInfo({
required this.update,
required this.version,
required this.notes,
required this.mandatory,
required this.sha256,
required this.download,
});
factory UpdateInfo.fromJson(Map<String, dynamic> json) {
return UpdateInfo(
update: json["update"] ?? false,
version: json["version"] ?? "",
notes: json["notes"] ?? "",
mandatory: json["mandatory"] ?? false,
sha256: json["sha256"] ?? "",
download: json["download"] ?? "",
);
}
}
class AppUpdateUtil {
final String serverUrl;
AppUpdateUtil({
required this.serverUrl,
});
/// Gets the installed app version
Future<String> currentVersion() async {
// final info =
// await PackageInfo.fromPlatform();
return "test";
}
/// Checks the update server
Future<UpdateInfo?> checkForUpdate() async {
final version =
await currentVersion();
final url = Uri.parse(
"$serverUrl/api/update?version=$version",
);
final response =
await http.get(url);
if (response.statusCode != 200) {
throw Exception(
"Update server unavailable",
);
}
final data =
jsonDecode(response.body);
if (data["update"] != true) {
return null;
}
return UpdateInfo.fromJson(data);
}
/// Downloads the APK
Future<File> downloadApk(UpdateInfo update, {
Function(double progress)? onProgress,
}) async {
final url =
update.download.startsWith("http")
? update.download
: "$serverUrl${update.download}";
final request =
http.Request(
"GET",
Uri.parse(url),
);
final response =
await request.send();
if (response.statusCode != 200) {
throw Exception(
"APK download failed",
);
}
final total =
response.contentLength ?? 0;
int received = 0;
final directory =
await getTemporaryDirectory();
final file =
File(
"${directory.path}/update.apk",
);
final sink =
file.openWrite();
await for (final chunk in response.stream) {
sink.add(chunk);
received += chunk.length;
if (total > 0 && onProgress != null) {
onProgress(
received / total,
);
}
}
await sink.close();
return file;
}
/// Verifies APK checksum
Future<bool> verifySha256(File file,
String expectedHash,) async {
final bytes =
await file.readAsBytes();
final digest =
sha256.convert(bytes);
return digest.toString()
.toLowerCase()
==
expectedHash.toLowerCase();
}
/// Opens Android APK installer
Future<void> installApk(File file,) async {
// final result =
// await OpenFilex.open(
// file.path,
// );
//
//
// if (result.type != ResultType.done) {
// throw Exception(
// "Could not open APK installer",
// );
// }
}
/// Full update flow
///
/// Returns:
/// - null if no update exists
/// - UpdateInfo if update is available
///
Future<UpdateInfo?> update({
Function(double progress)? onProgress,
}) async {
final info =
await checkForUpdate();
if (info == null) {
return null;
}
final apk =
await downloadApk(
info,
onProgress: onProgress,
);
final valid =
await verifySha256(
apk,
info.sha256,
);
if (!valid) {
throw Exception(
"APK checksum mismatch",
);
}
await installApk(
apk,
);
return info;
}
}
+20 -8
View File
@@ -8,9 +8,11 @@ import '../services/product_service.dart';
class BarScreenViewModel extends ChangeNotifier {
final BarTabService barTabService;
final ProductService productService;
BarScreenViewModel({
required this.barTabService,
required this.productService,
});
List<BarTab> _tabs = [];
@@ -74,9 +76,7 @@ class BarScreenViewModel extends ChangeNotifier {
}
Future<void> createTab(String customerName) async {
final tab = await barTabService.createTab(
customerName: customerName,
);
final tab = await barTabService.createTab(customerName: customerName);
_selectedTabId = tab.id;
await _reloadTabs();
@@ -87,23 +87,34 @@ class BarScreenViewModel extends ChangeNotifier {
if (tab == null) return;
if (product.stockQuantity <= 0) {
throw Exception('Product is out of stock.');
}
await barTabService.addProductToTab(
tabId: tab.id,
product: product,
);
await productService.decreaseStock(product.id, 1);
await _reloadTabs();
}
Future<void> changeItemQuantity(
TabItem item,
int quantity,
) async {
Future<void> changeItemQuantity(TabItem item, int quantity) async {
final difference = quantity - item.quantity;
await barTabService.updateTabItemQuantity(
tabItemId: item.id,
quantity: quantity,
);
if (difference > 0) {
await productService.decreaseStock(item.productId, difference);
} else if (difference < 0) {
await productService.increaseStock(item.productId, -difference);
}
await _reloadTabs();
}
@@ -126,7 +137,8 @@ class BarScreenViewModel extends ChangeNotifier {
Future<void> _reloadTabs() async {
_tabs = await barTabService.getOpenTabs();
if (_selectedTabId == null || !_tabs.any((tab) => tab.id == _selectedTabId)) {
if (_selectedTabId == null ||
!_tabs.any((tab) => tab.id == _selectedTabId)) {
_selectedTabId = _tabs.isEmpty ? null : _tabs.first.id;
}
@@ -56,6 +56,20 @@ class ProductListViewModel extends ChangeNotifier {
_isLoading = false;
notifyListeners();
}
try {
_products = await productService.getProducts();
debugPrint(
_products.map((p) => '${p.name}: ${p.stockQuantity}').join('\n'),
);
} catch (_) {
_errorMessage = 'Could not load products.';
} finally {
_hasLoaded = true;
_isLoading = false;
notifyListeners();
}
}
Future<void> addProduct({
+66
View File
@@ -0,0 +1,66 @@
import 'package:flutter/foundation.dart';
import '../models/settings.dart';
import '../services/settings_service.dart';
class SettingsViewModel extends ChangeNotifier {
final SettingsService settingsService;
SettingsViewModel({required this.settingsService});
AppSettings _settings = AppSettings.defaults;
bool _isLoading = false;
bool _hasLoaded = false;
String? _errorMessage;
AppSettings get settings => _settings;
bool get isLoading => _isLoading;
bool get hasLoaded => _hasLoaded;
String? get errorMessage => _errorMessage;
Future<void> ensureLoaded() async {
if (_hasLoaded || _isLoading) return;
await load();
}
Future<void> load() async {
if (_isLoading) return;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
_settings = await settingsService.getSettings();
} catch (_) {
_errorMessage = 'Could not load settings.';
} finally {
_hasLoaded = true;
_isLoading = false;
notifyListeners();
}
}
/// Just flips the preference flag. Caller is responsible for having
/// already set/verified the actual PIN via PinLockViewModel first.
Future<void> updatePinRequired(bool value) =>
_save(_settings.copyWith(pinRequired: value));
Future<void> updateThemeMode(AppThemeMode mode) =>
_save(_settings.copyWith(themeMode: mode));
Future<void> _save(AppSettings updated) async {
final previous = _settings;
_settings = updated;
_errorMessage = null;
notifyListeners();
try {
await settingsService.saveSettings(updated);
} catch (_) {
_settings = previous;
_errorMessage = 'Could not save settings.';
notifyListeners();
}
}
}
+25 -24
View File
@@ -1,6 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widget_previews.dart';
import 'package:go_router/go_router.dart';
import 'package:kooltab2/viewmodels/pin_lock_view_model.dart';
import 'package:kooltab2/viewmodels/product_list_view_model.dart';
@@ -43,6 +41,12 @@ class BarScreenView extends StatelessWidget {
icon: const Icon(Icons.refresh_rounded),
),
const SizedBox(width: 6),
IconButton(
tooltip: 'Settings',
onPressed: () => context.go('/settings'),
icon: const Icon(Icons.settings),
),
const SizedBox(width: 6),
IconButton(
tooltip: 'logout',
onPressed: (){
@@ -234,12 +238,12 @@ class _ProductGrid extends StatelessWidget {
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: scheme.onSurface.withOpacity(0.05),
color: scheme.onSurface.withValues(alpha: 0.05),
),
child: Icon(
Icons.inventory_2_outlined,
size: 40,
color: scheme.onSurface.withOpacity(0.3),
color: scheme.onSurface.withValues(alpha: 0.3),
),
),
const SizedBox(height: 16),
@@ -280,7 +284,7 @@ class _ProductGrid extends StatelessWidget {
vertical: 4,
),
decoration: BoxDecoration(
color: scheme.onSurface.withOpacity(0.06),
color: scheme.onSurface.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(999),
),
child: Row(
@@ -289,7 +293,7 @@ class _ProductGrid extends StatelessWidget {
Icon(
Icons.info_outline_rounded,
size: 14,
color: scheme.onSurface.withOpacity(0.5),
color: scheme.onSurface.withValues(alpha: 0.5),
),
const SizedBox(width: 4),
Flexible(
@@ -369,7 +373,7 @@ class _ProductTile extends StatelessWidget {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
border: Border.all(color: scheme.onSurface.withOpacity(0.08), width: 1),
border: Border.all(color: scheme.onSurface.withValues(alpha: 0.08), width: 1),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
@@ -396,7 +400,7 @@ class _ProductTile extends StatelessWidget {
Icon(
Icons.image_not_supported_outlined,
size: 34,
color: scheme.onSurface.withOpacity(0.3),
color: scheme.onSurface.withValues(alpha: 0.3),
),
const SizedBox(height: 6),
Text(
@@ -406,9 +410,6 @@ class _ProductTile extends StatelessWidget {
],
),
),
// Scrim stays black regardless of theme — it's for legibility
// of the (usually light/photographic) image beneath it, not
// themed UI chrome.
if (_hasImage)
Positioned.fill(
child: DecoratedBox(
@@ -418,7 +419,7 @@ class _ProductTile extends StatelessWidget {
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black.withOpacity(0.35),
Colors.black.withValues(alpha: 0.35),
],
stops: const [0.6, 1.0],
),
@@ -541,7 +542,7 @@ class _TabPanelState extends State<_TabPanel> {
vertical: 2,
),
decoration: BoxDecoration(
color: scheme.onSurface.withOpacity(0.06),
color: scheme.onSurface.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(999),
),
child: Text(
@@ -577,7 +578,7 @@ class _TabPanelState extends State<_TabPanel> {
Icon(
Icons.receipt_long_outlined,
size: 36,
color: scheme.onSurface.withOpacity(0.25),
color: scheme.onSurface.withValues(alpha: 0.25),
),
const SizedBox(height: 10),
Text(
@@ -627,7 +628,7 @@ class _OpenTabsList extends StatelessWidget {
return ListView.separated(
itemCount: tabs.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
separatorBuilder: (_, _) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final tab = tabs[index];
final selected = tab.id == selectedTabId;
@@ -665,13 +666,13 @@ class _OpenTabsList extends StatelessWidget {
duration: const Duration(milliseconds: 150),
decoration: BoxDecoration(
color: selected
? primary.withOpacity(0.14)
: scheme.onSurface.withOpacity(0.04),
? primary.withValues(alpha: 0.14)
: scheme.onSurface.withValues(alpha: 0.04),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: selected
? primary.withOpacity(0.6)
: scheme.onSurface.withOpacity(0.06),
? primary.withValues(alpha: 0.6)
: scheme.onSurface.withValues(alpha: 0.06),
width: selected ? 1.4 : 1,
),
),
@@ -764,7 +765,7 @@ class _SelectedTabDetails extends StatelessWidget {
Icon(
Icons.local_bar_outlined,
size: 32,
color: scheme.onSurface.withOpacity(0.25),
color: scheme.onSurface.withValues(alpha: 0.25),
),
const SizedBox(height: 8),
Text(
@@ -776,7 +777,7 @@ class _SelectedTabDetails extends StatelessWidget {
)
: ListView.separated(
itemCount: tab.items.length,
separatorBuilder: (_, __) => const Divider(height: 1),
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final item = tab.items[index];
@@ -791,10 +792,10 @@ class _SelectedTabDetails extends StatelessWidget {
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary.withOpacity(0.12),
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.3),
),
),
child: Row(
@@ -858,7 +859,7 @@ class _TabItemRow extends StatelessWidget {
),
Container(
decoration: BoxDecoration(
color: scheme.onSurface.withOpacity(0.05),
color: scheme.onSurface.withValues(alpha: 0.05),
borderRadius: BorderRadius.circular(999),
),
child: Row(
+6 -6
View File
@@ -118,7 +118,7 @@ class _HistoryScreenViewState extends State<HistoryScreenView> with RouteAware {
: ListView.separated(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 20),
itemCount: viewModel.closedTabs.length,
separatorBuilder: (_, __) => const SizedBox(height: 10),
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final closedTab = viewModel.closedTabs[index];
@@ -147,12 +147,12 @@ class _EmptyState extends StatelessWidget {
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: scheme.onSurface.withOpacity(0.05),
color: scheme.onSurface.withValues(alpha: 0.05),
),
child: Icon(
Icons.history_rounded,
size: 40,
color: scheme.onSurface.withOpacity(0.3),
color: scheme.onSurface.withValues(alpha: 0.3),
),
),
const SizedBox(height: 16),
@@ -191,9 +191,9 @@ class _ClosedTabCardState extends State<_ClosedTabCard> {
return Container(
decoration: BoxDecoration(
color: scheme.onSurface.withOpacity(0.04),
color: scheme.onSurface.withValues(alpha: 0.04),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: scheme.onSurface.withOpacity(0.06)),
border: Border.all(color: scheme.onSurface.withValues(alpha: 0.06)),
),
clipBehavior: Clip.antiAlias,
child: Material(
@@ -249,7 +249,7 @@ class _ClosedTabCardState extends State<_ClosedTabCard> {
_expanded
? Icons.expand_less_rounded
: Icons.expand_more_rounded,
color: scheme.onSurface.withOpacity(0.5),
color: scheme.onSurface.withValues(alpha: 0.5),
),
],
),
+4 -4
View File
@@ -210,7 +210,7 @@ class _PinDots extends StatelessWidget {
shape: BoxShape.circle,
color: isFilled ? scheme.primary : Colors.transparent,
border: Border.all(
color: isFilled ? scheme.primary : scheme.onSurface.withOpacity(0.3),
color: isFilled ? scheme.primary : scheme.onSurface.withValues(alpha: 0.3),
width: 1.4,
),
),
@@ -305,21 +305,21 @@ class _KeypadButton extends StatelessWidget {
width: 72,
height: 72,
child: Material(
color: scheme.onSurface.withOpacity(0.04),
color: scheme.onSurface.withValues(alpha: 0.04),
shape: const CircleBorder(),
child: InkWell(
customBorder: const CircleBorder(),
onTap: onTap,
child: Center(
child: icon != null
? Icon(icon, color: scheme.onSurface.withOpacity(0.8))
? Icon(icon, color: scheme.onSurface.withValues(alpha: 0.8))
: Text(
label!,
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
color: onTap == null
? scheme.onSurface.withOpacity(0.3)
? scheme.onSurface.withValues(alpha: 0.3)
: scheme.onSurface,
),
),
+17 -2
View File
@@ -6,9 +6,24 @@ import 'package:provider/provider.dart';
import '../viewmodels/product_list_view_model.dart';
class ProductListView extends StatelessWidget {
class ProductListView extends StatefulWidget {
const ProductListView({super.key});
@override
State<ProductListView> createState() => _ProductListViewState();
}
class _ProductListViewState extends State<ProductListView> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<ProductListViewModel>().loadProducts();
});
}
@override
Widget build(BuildContext context) {
final viewModel = context.watch<ProductListViewModel>();
@@ -53,7 +68,7 @@ class ProductListView extends StatelessWidget {
return ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: viewModel.products.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
separatorBuilder: (_, _) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final product = viewModel.products[index];
+345
View File
@@ -0,0 +1,345 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../models/settings.dart';
import '../viewmodels/pin_lock_view_model.dart';
import '../viewmodels/settings_view_model.dart';
class SettingsScreenView extends StatefulWidget {
const SettingsScreenView({super.key});
@override
State<SettingsScreenView> createState() => _SettingsScreenViewState();
}
class _SettingsScreenViewState extends State<SettingsScreenView> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<SettingsViewModel>().ensureLoaded();
context.read<PinLockViewModel>().ensureLoaded();
});
}
Future<String?> _promptPin(String title, {String hint = 'Enter PIN'}) {
final controller = TextEditingController();
return showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: TextField(
controller: controller,
autofocus: true,
obscureText: true,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(hintText: hint),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, controller.text),
child: const Text('Confirm'),
),
],
),
);
}
void _showError(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
}
Future<void> _enablePin() async {
final pin = await _promptPin('Set PIN Code', hint: '46 digits');
if (pin == null) return;
if (pin.length < 4) {
_showError('PIN must be at least 4 digits');
return;
}
final pinLockViewModel = context.read<PinLockViewModel>();
final success = await pinLockViewModel.setPin(pin);
if (!success) {
_showError(pinLockViewModel.errorMessage ?? 'Could not set PIN.');
return;
}
await context.read<SettingsViewModel>().updatePinRequired(true);
}
Future<void> _changePin() async {
final current = await _promptPin('Enter Current PIN');
if (current == null) return;
final newPin = await _promptPin('Enter New PIN', hint: '46 digits');
if (newPin == null) return;
if (newPin.length < 4) {
_showError('PIN must be at least 4 digits');
return;
}
final pinLockViewModel = context.read<PinLockViewModel>();
final success = await pinLockViewModel.changePin(
currentPin: current,
newPin: newPin,
);
if (!success) {
_showError(pinLockViewModel.errorMessage ?? 'Could not change PIN.');
}
}
Future<void> _disablePin() async {
final current = await _promptPin('Enter Current PIN to Disable');
if (current == null) return;
final pinLockViewModel = context.read<PinLockViewModel>();
final success = await pinLockViewModel.disablePin(current);
if (!success) {
_showError(pinLockViewModel.errorMessage ?? 'Could not disable PIN.');
return;
}
await context.read<SettingsViewModel>().updatePinRequired(false);
}
@override
Widget build(BuildContext context) {
final settingsViewModel = context.watch<SettingsViewModel>();
final pinLockViewModel = context.watch<PinLockViewModel>();
return Scaffold(
appBar: AppBar(
title: Row(
children: [
IconButton(
onPressed: () => context.go('/bar'),
icon: const Icon(Icons.arrow_back),
),
const SizedBox(width: 5),
const Text('Settings'),
],
),
),
body: Builder(
builder: (context) {
final isLoading = settingsViewModel.isLoading || pinLockViewModel.isLoading;
final hasLoaded = settingsViewModel.hasLoaded && pinLockViewModel.hasLoaded;
if (isLoading && !hasLoaded) {
return const Center(
child: CircularProgressIndicator(strokeWidth: 2.5),
);
}
final settings = settingsViewModel.settings;
return ListView(
padding: const EdgeInsets.symmetric(vertical: 12),
children: [
_SettingsSection(
title: 'Security',
children: [
_SettingsSwitchTile(
icon: Icons.lock_outline_rounded,
title: 'PIN Required',
value: settings.pinRequired,
onChanged: (value) {
if (value) {
_enablePin();
} else {
_disablePin();
}
},
),
if (settings.pinRequired)
_SettingsTile(
icon: Icons.pin_rounded,
title: 'Change PIN',
onTap: _changePin,
),
],
),
_SettingsSection(
title: 'Appearance',
children: [
_SettingsTile(
icon: Icons.brightness_6_rounded,
title: 'Theme',
subtitle: switch (settings.themeMode) {
AppThemeMode.system => 'System',
AppThemeMode.light => 'Light',
AppThemeMode.dark => 'Dark',
},
onTap: () async {
final selected = await showModalBottomSheet<AppThemeMode>(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: AppThemeMode.values.map((mode) {
return RadioListTile<AppThemeMode>(
value: mode,
groupValue: settings.themeMode,
title: Text(switch (mode) {
AppThemeMode.system => 'System',
AppThemeMode.light => 'Light',
AppThemeMode.dark => 'Dark',
}),
onChanged: (value) => Navigator.pop(context, value),
);
}).toList(),
),
),
);
if (selected != null) {
await settingsViewModel.updateThemeMode(selected);
}
},
),
],
),
],
);
},
),
);
}
}
class _SettingsSection extends StatelessWidget {
final String title;
final List<Widget> children;
const _SettingsSection({required this.title, required this.children});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title.toUpperCase(),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
letterSpacing: 0.5,
color: scheme.onSurface.withValues(alpha: 0.5),
),
),
const SizedBox(height: 8),
Container(
decoration: BoxDecoration(
color: scheme.onSurface.withValues(alpha: 0.04),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: scheme.onSurface.withValues(alpha: 0.06)),
),
clipBehavior: Clip.antiAlias,
child: Column(children: children),
),
],
),
);
}
}
class _SettingsTile extends StatelessWidget {
final IconData icon;
final String title;
final String? subtitle;
final VoidCallback? onTap;
const _SettingsTile({
required this.icon,
required this.title,
this.subtitle,
this.onTap,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
children: [
Icon(icon, size: 22, color: scheme.onSurface.withValues(alpha: 0.7)),
const SizedBox(width: 14),
Expanded(
child: Text(
title,
style: TextStyle(fontWeight: FontWeight.w600, color: scheme.onSurface),
),
),
if (subtitle != null) ...[
Text(subtitle!, style: Theme.of(context).textTheme.bodySmall),
const SizedBox(width: 4),
],
if (onTap != null)
Icon(Icons.chevron_right_rounded, color: scheme.onSurface.withValues(alpha: 0.3)),
],
),
),
),
);
}
}
class _SettingsSwitchTile extends StatelessWidget {
final IconData icon;
final String title;
final bool value;
final ValueChanged<bool> onChanged;
const _SettingsSwitchTile({
required this.icon,
required this.title,
required this.value,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
Icon(icon, size: 22, color: scheme.onSurface.withValues(alpha: 0.7)),
const SizedBox(width: 14),
Expanded(
child: Text(
title,
style: TextStyle(fontWeight: FontWeight.w600, color: scheme.onSurface),
),
),
Switch(value: value, onChanged: onChanged),
],
),
);
}
}
+4
View File
@@ -46,6 +46,10 @@ dependencies:
intl: ^0.20.3
flutter_secure_storage: ^9.0.0
crypto: ^3.0.0
# http: ^1.6.0
# package_info_plus: ^10.2.1
# open_filex: ^4.7.0
# permission_handler: ^12.0.3
dev_dependencies:
-3
View File
@@ -5,10 +5,7 @@
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:kooltab2/main.dart';
void main() {
}