1 Commits

Author SHA1 Message Date
0f79495775 Implemented badges
All checks were successful
Pull Request Pipeline / lint (pull_request) Successful in 2m25s
Pull Request Pipeline / test (pull_request) Successful in 2m27s
2025-12-06 15:42:02 +01:00
62 changed files with 2692 additions and 3531 deletions

View File

@@ -1,7 +1,15 @@
# Game Tracker # Game Tracker
![Version](https://img.shields.io/badge/Version-0.3.0-orange) ![Flutter](https://img.shields.io/badge/Created_by-Liquid_Development-027DFD?logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyBpZD0iRWJlbmVfMSIgZGF0YS1uYW1lPSJFYmVuZSAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA3MjUuNDggODk3LjMiPgogIDxkZWZzPgogICAgPHN0eWxlPgogICAgICAuY2xzLTEgewogICAgICAgIGZpbGw6ICNmZmY7CiAgICAgIH0KICAgIDwvc3R5bGU+CiAgPC9kZWZzPgogIDxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTcwNS4yNiw3MDEuOTJsNi40LDExLjA4Yy0xLjk1LTMuODEtNC4wOS03LjUxLTYuNC0xMS4wOFoiLz4KICA8cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik02MDIuMzksODk3LjI1aC03LjIxYzEuMi4wMywyLjQuMDUsMy42MS4wNXMyLjQxLS4wMiwzLjYxLS4wNVoiLz4KICA8cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0wLDY5NS4zOGwyLjY4LTQuNjRjLS45MywxLjUyLTEuODIsMy4wNy0yLjY4LDQuNjRaIi8+CiAgPHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNjgyLjU1LDcyMy40NWw2LjA1LDEwLjQ5Yy0xLjc5LTMuNjQtMy44MS03LjE1LTYuMDUtMTAuNDlaIi8+CiAgPHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMzcuNzIsNzMzLjI4bDUuMy05LjE4Yy0xLjk0LDIuOTQtMy43MSw2LjAxLTUuMyw5LjE4WiIvPgogIDxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTcxMS42Niw3MTMuMDFsLTYuNC0xMS4wOC0yMjAuNDYtMzgxLjg0aDBWMTAxLjg0YzIwLjY3LTYuOTgsMzUuNTYtMjYuNTIsMzUuNTYtNDkuNTQsMC0yOC44OC0yMy40MS01Mi4zLTUyLjMtNTIuM2gtMjA5LjQ4Yy0yOC44OCwwLTUyLjMsMjMuNDEtNTIuMyw1Mi4zLDAsMjIuNzEsMTQuNDgsNDIuMDMsMzQuNyw0OS4yNXYyMTguNTRsLS4zMy41OEwxOC44OSw3MDQuNzlsLTIuNjgsNC42NGMtOS45OSwxOC4xMi0xNS42OCwzOC45Ni0xNS42OCw2MS4xMiwwLDY5Ljk3LDU2LjY0LDEyNi43LDEyNi41MSwxMjYuN2g0NzUuMzVjNjguMy0xLjkxLDEyMy4wOS01Ny44OCwxMjMuMDktMTI2LjY0LDAtMjAuNzQtNC45OS00MC4zMi0xMy44Mi01Ny42Wk02MDguNTYsODYyLjUzSDExNy40M2MtNDkuMzcsMC04OS4zOS00MC4wMi04OS4zOS04OS4zOSwwLTE0LjM2LDMuMzktMjcuOTMsOS40MS0zOS45Nmw1LjMtOS4xOCwyMzMuMi00MDMuOTJoLS4wOFYxMDQuNTloMTcuODFjOS40NywwLDE3LjE1LTcuNjgsMTcuMTUtMTcuMTVzLTcuNjgtMTcuMTUtMTcuMTUtMTcuMTVoLTM1LjU5di0uMDJjLTkuNzItLjI2LTE3LjUyLTguMi0xNy41Mi0xNy45OHM3LjgtMTcuNzIsMTcuNTItMTcuOTh2LS4wMmgyMDkuMjZjOS45NCwwLDE4LDguMDYsMTgsMThzLTguMDYsMTgtMTgsMThoLTM0LjQ4Yy05LjQ3LDAtMTcuMTUsNy42OC0xNy4xNSwxNy4xNXM3LjY4LDE3LjE1LDE3LjE1LDE3LjE1aDE3LjA0djIxNS40OWguMDdsMjMyLjgyLDQwMy4yNiw2LjA2LDEwLjVjNS44MiwxMS44Niw5LjA5LDI1LjIsOS4wOSwzOS4zLDAsNDkuMzctNDAuMDIsODkuMzktODkuMzksODkuMzlaIi8+CiAgPHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMzgxLjY4LDU0NS4zOGMtMy4wOCwxLjY4LTYuMTgsMy4zLTkuMzIsNC44NiwzLjA3LTEuNjcsNi4xOC0zLjI5LDkuMzItNC44NloiLz4KICA8cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik01ODMuNDIsNTUxLjE5bC0yMC42Ny0zNS44Yy0xMy42OS0xLjg0LTI3LjY3LTIuNzktNDEuODYtMi43OS0xNy45OSwwLTM1LjYyLDEuNTMtNTIuNzgsNC40Ni0zMC41Niw1LjIxLTU5LjYsMTQuODktODYuNDIsMjguMzMtMy4wOCwxLjY4LTYuMTgsMy4zLTkuMzIsNC44Ni00MS44OCwyMC45OS04OS4xNiwzMi43OS0xMzkuMTksMzIuNzktMzQuODUsMC02OC4zNS01Ljc0LTk5LjYzLTE2LjMxLDAsMCwwLC4wMiwwLC4wMmwtMTYuNTIsMjguNjFjMzcuMDEsMTUuNTMsNzcuNjUsMjQuMTIsMTIwLjMsMjQuMTIsMTcuOTgsMCwzNS42MS0xLjUzLDUyLjc2LTQuNDYsMzIuNzctNS41OSw2My43OC0xNi4zMSw5Mi4yLTMxLjI5Ljg3LS40NiwxLjczLS45MiwyLjYtMS40LDQzLjI5LTIyLjgyLDkyLjYyLTM1Ljc0LDE0NC45Ni0zNS43NCwxOC4yOCwwLDM2LjE4LDEuNTksNTMuNTksNC42MWwtLjAyLS4wMloiLz4KICA8Zz4KICAgIDxjaXJjbGUgY2xhc3M9ImNscy0xIiBjeD0iNTg3LjY0IiBjeT0iODAzLjQiIHI9IjE4Ljk2Ii8+CiAgICA8cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik01MTUuNTIsNzg0LjQzSDEwMy41NWMtMTAuOTIsMC0xOS43Niw4LjQ5LTE5Ljc2LDE4Ljk2czguODUsMTguOTYsMTkuNzYsMTguOTZoNDExLjk3YzEwLjkyLDAsMTkuNzYtOC40OSwxOS43Ni0xOC45NnMtOC44NS0xOC45Ni0xOS43Ni0xOC45NloiLz4KICA8L2c+CiAgPGNpcmNsZSBjbGFzcz0iY2xzLTEiIGN4PSIyODMuMzIiIGN5PSI0NjcuNTkiIHI9IjE4Ljk2Ii8+CiAgPGNpcmNsZSBjbGFzcz0iY2xzLTEiIGN4PSIzMjYuMjMiIGN5PSIzNjYuMjUiIHI9IjE4Ljk2Ii8+CiAgPHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDA2LjU2LDM4NS4yMmMtMjQuMDYsMC00My41NiwxOS41LTQzLjU2LDQzLjU2czE5LjUsNDMuNTYsNDMuNTYsNDMuNTYsNDMuNTYtMTkuNSw0My41Ni00My41Ni0xOS41LTQzLjU2LTQzLjU2LTQzLjU2Wk00MDYuNTYsNDQ3Ljc0Yy0xMC40NywwLTE4Ljk2LTguNDktMTguOTYtMTguOTZzOC40OS0xOC45NiwxOC45Ni0xOC45NiwxOC45Niw4LjQ5LDE4Ljk2LDE4Ljk2LTguNDksMTguOTYtMTguOTYsMTguOTZaIi8+Cjwvc3ZnPg==)
![Flutter](https://img.shields.io/badge/Flutter-3.32.1-blue?logo=flutter)
![Dart](https://img.shields.io/badge/Dart-3.8.1-blue?logo=dart) ![Version](https://img.shields.io/badge/App--Version-MVP-orange)
![Flutter](https://img.shields.io/badge/Flutter-3.35.6-027DFD?logo=flutter)
![Dart](https://img.shields.io/badge/Dart-3.9.2-027DFD?logo=dart)
### Versions Supported
![iOS18](https://img.shields.io/badge/iOS-18.7.1-white?logo=apple)
![iOS26](https://img.shields.io/badge/iOS-26.1-white?logo=apple)
![Android16](https://img.shields.io/badge/Android-16-3DDC84?logo=android)
A all-in-one app to track card- and board games, manage players and groups and get statistics about your played games. A all-in-one app to track card- and board games, manage players and groups and get statistics about your played games.

View File

@@ -6,7 +6,6 @@
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
android:screenOrientation="portrait"
android:launchMode="singleTop" android:launchMode="singleTop"
android:taskAffinity="" android:taskAffinity=""
android:theme="@style/LaunchTheme" android:theme="@style/LaunchTheme"

View File

@@ -31,6 +31,8 @@
<key>UISupportedInterfaceOrientations</key> <key>UISupportedInterfaceOrientations</key>
<array> <array>
<string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array> </array>
<key>UISupportedInterfaceOrientations~ipad</key> <key>UISupportedInterfaceOrientations~ipad</key>
<array> <array>

View File

@@ -1,4 +0,0 @@
arb-dir: lib/l10n/arb
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
output-dir: lib/l10n/generated

View File

@@ -1,2 +0,0 @@
/// Minimum duration of all app skeletons
Duration minimumSkeletonDuration = const Duration(milliseconds: 250);

View File

@@ -1,6 +1,3 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
/// Button types used for styling the [CustomWidthButton] /// Button types used for styling the [CustomWidthButton]
enum ButtonType { primary, secondary, tertiary } enum ButtonType { primary, secondary, tertiary }
@@ -26,23 +23,9 @@ enum ImportResult {
/// - [ExportResult.unknownException]: An exception occurred during export. /// - [ExportResult.unknownException]: An exception occurred during export.
enum ExportResult { success, canceled, unknownException } enum ExportResult { success, canceled, unknownException }
/// Different rulesets available for matches /// Different rulesets available for games
/// - [Ruleset.singleWinner]: The match is won by a single player /// - [Ruleset.singleWinner]: The game is won by a single player
/// - [Ruleset.singleLoser]: The match is lost by a single player /// - [Ruleset.singleLoser]: The game is lost by a single player
/// - [Ruleset.mostPoints]: The player with the most points wins. /// - [Ruleset.mostPoints]: The player with the most points wins.
/// - [Ruleset.leastPoints]: The player with the fewest points wins. /// - [Ruleset.lastPoints]: The player with the fewest points wins.
enum Ruleset { singleWinner, singleLoser, mostPoints, leastPoints } enum Ruleset { singleWinner, singleLoser, mostPoints, lastPoints }
/// Translates a [Ruleset] enum value to its corresponding localized string.
String translateRulesetToString(Ruleset ruleset, BuildContext context) {
switch (ruleset) {
case Ruleset.singleWinner:
return AppLocalizations.of(context)!.single_winner;
case Ruleset.singleLoser:
return AppLocalizations.of(context)!.single_loser;
case Ruleset.mostPoints:
return AppLocalizations.of(context)!.most_points;
case Ruleset.leastPoints:
return AppLocalizations.of(context)!.least_points;
}
}

320
lib/data/dao/game_dao.dart Normal file
View File

@@ -0,0 +1,320 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/game_table.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart';
part 'game_dao.g.dart';
@DriftAccessor(tables: [GameTable])
class GameDao extends DatabaseAccessor<AppDatabase> with _$GameDaoMixin {
GameDao(super.db);
/// Retrieves all games from the database.
Future<List<Game>> getAllGames() async {
final query = select(gameTable);
final result = await query.get();
return Future.wait(
result.map((row) async {
final group = await db.groupGameDao.getGroupOfGame(gameId: row.id);
final players = await db.playerGameDao.getPlayersOfGame(gameId: row.id);
final winner = row.winnerId != null
? await db.playerDao.getPlayerById(playerId: row.winnerId!)
: null;
return Game(
id: row.id,
name: row.name,
group: group,
players: players,
createdAt: row.createdAt,
winner: winner,
);
}),
);
}
/// Retrieves a [Game] by its [gameId].
Future<Game> getGameById({required String gameId}) async {
final query = select(gameTable)..where((g) => g.id.equals(gameId));
final result = await query.getSingle();
List<Player>? players;
if (await db.playerGameDao.gameHasPlayers(gameId: gameId)) {
players = await db.playerGameDao.getPlayersOfGame(gameId: gameId);
}
Group? group;
if (await db.groupGameDao.gameHasGroup(gameId: gameId)) {
group = await db.groupGameDao.getGroupOfGame(gameId: gameId);
}
Player? winner;
if (result.winnerId != null) {
winner = await db.playerDao.getPlayerById(playerId: result.winnerId!);
}
return Game(
id: result.id,
name: result.name,
players: players,
group: group,
winner: winner,
createdAt: result.createdAt,
);
}
/// Adds a new [Game] to the database.
/// Also adds associated players and group if they exist.
Future<void> addGame({required Game game}) async {
await db.transaction(() async {
await into(gameTable).insert(
GameTableCompanion.insert(
id: game.id,
name: game.name,
winnerId: Value(game.winner?.id),
createdAt: game.createdAt,
),
mode: InsertMode.insertOrReplace,
);
if (game.players != null) {
await db.playerDao.addPlayersAsList(players: game.players!);
for (final p in game.players ?? []) {
await db.playerGameDao.addPlayerToGame(
gameId: game.id,
playerId: p.id,
);
}
}
if (game.group != null) {
await db.groupDao.addGroup(group: game.group!);
await db.groupGameDao.addGroupToGame(
gameId: game.id,
groupId: game.group!.id,
);
}
});
}
/// Adds multiple [Game]s to the database in a batch operation.
/// Also adds associated players and groups if they exist.
/// If the [games] list is empty, the method returns immediately.
Future<void> addGamesAsList({required List<Game> games}) async {
if (games.isEmpty) return;
await db.transaction(() async {
// Add all games in batch
await db.batch(
(b) => b.insertAll(
gameTable,
games
.map(
(game) => GameTableCompanion.insert(
id: game.id,
name: game.name,
createdAt: game.createdAt,
winnerId: Value(game.winner?.id),
),
)
.toList(),
mode: InsertMode.insertOrReplace,
),
);
// Add all groups of the games in batch
await db.batch(
(b) => b.insertAll(
db.groupTable,
games
.where((game) => game.group != null)
.map(
(game) => GroupTableCompanion.insert(
id: game.group!.id,
name: game.group!.name,
createdAt: game.group!.createdAt,
),
)
.toList(),
mode: InsertMode.insertOrReplace,
),
);
// Add all players of the games in batch (unique)
final uniquePlayers = <String, Player>{};
for (final game in games) {
if (game.players != null) {
for (final p in game.players!) {
uniquePlayers[p.id] = p;
}
}
// Also include members of groups
if (game.group != null) {
for (final m in game.group!.members) {
uniquePlayers[m.id] = m;
}
}
}
if (uniquePlayers.isNotEmpty) {
await db.batch(
(b) => b.insertAll(
db.playerTable,
uniquePlayers.values
.map(
(p) => PlayerTableCompanion.insert(
id: p.id,
name: p.name,
createdAt: p.createdAt,
),
)
.toList(),
mode: InsertMode.insertOrReplace,
),
);
}
// Add all player-game associations in batch
await db.batch((b) {
for (final game in games) {
if (game.players != null) {
for (final p in game.players ?? []) {
b.insert(
db.playerGameTable,
PlayerGameTableCompanion.insert(
gameId: game.id,
playerId: p.id,
),
mode: InsertMode.insertOrReplace,
);
}
}
}
});
// Add all player-group associations in batch
await db.batch((b) {
for (final game in games) {
if (game.group != null) {
for (final m in game.group!.members) {
b.insert(
db.playerGroupTable,
PlayerGroupTableCompanion.insert(
playerId: m.id,
groupId: game.group!.id,
),
mode: InsertMode.insertOrReplace,
);
}
}
}
});
// Add all group-game associations in batch
await db.batch((b) {
for (final game in games) {
if (game.group != null) {
b.insert(
db.groupGameTable,
GroupGameTableCompanion.insert(
gameId: game.id,
groupId: game.group!.id,
),
mode: InsertMode.insertOrReplace,
);
}
}
});
});
}
/// Deletes the game with the given [gameId] from the database.
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> deleteGame({required String gameId}) async {
final query = delete(gameTable)..where((g) => g.id.equals(gameId));
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Retrieves the number of games in the database.
Future<int> getGameCount() async {
final count =
await (selectOnly(gameTable)..addColumns([gameTable.id.count()]))
.map((row) => row.read(gameTable.id.count()))
.getSingle();
return count ?? 0;
}
/// Checks if a game with the given [gameId] exists in the database.
/// Returns `true` if the game exists, otherwise `false`.
Future<bool> gameExists({required String gameId}) async {
final query = select(gameTable)..where((g) => g.id.equals(gameId));
final result = await query.getSingleOrNull();
return result != null;
}
/// Deletes all games from the database.
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> deleteAllGames() async {
final query = delete(gameTable);
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Sets the winner of the game with the given [gameId] to the player with
/// the given [winnerId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> setWinner({
required String gameId,
required String winnerId,
}) async {
final query = update(gameTable)..where((g) => g.id.equals(gameId));
final rowsAffected = await query.write(
GameTableCompanion(winnerId: Value(winnerId)),
);
return rowsAffected > 0;
}
/// Retrieves the winner of the game with the given [gameId].
/// Returns the [Player] who won the game, or `null` if no winner is set.
Future<Player?> getWinner({required String gameId}) async {
final query = select(gameTable)..where((g) => g.id.equals(gameId));
final result = await query.getSingleOrNull();
if (result == null || result.winnerId == null) {
return null;
}
final winner = await db.playerDao.getPlayerById(playerId: result.winnerId!);
return winner;
}
/// Removes the winner of the game with the given [gameId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> removeWinner({required String gameId}) async {
final query = update(gameTable)..where((g) => g.id.equals(gameId));
final rowsAffected = await query.write(
const GameTableCompanion(winnerId: Value(null)),
);
return rowsAffected > 0;
}
/// Checks if the game with the given [gameId] has a winner set.
/// Returns `true` if a winner is set, otherwise `false`.
Future<bool> hasWinner({required String gameId}) async {
final query = select(gameTable)
..where((g) => g.id.equals(gameId) & g.winnerId.isNotNull());
final result = await query.getSingleOrNull();
return result != null;
}
/// Changes the title of the game with the given [gameId] to [newName].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> updateGameName({
required String gameId,
required String newName,
}) async {
final query = update(gameTable)..where((g) => g.id.equals(gameId));
final rowsAffected = await query.write(
GameTableCompanion(name: Value(newName)),
);
return rowsAffected > 0;
}
}

View File

@@ -0,0 +1,8 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'game_dao.dart';
// ignore_for_file: type=lint
mixin _$GameDaoMixin on DatabaseAccessor<AppDatabase> {
$GameTableTable get gameTable => attachedDatabase.gameTable;
}

View File

@@ -1,13 +1,12 @@
import 'package:drift/drift.dart'; import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/group_table.dart'; import 'package:game_tracker/data/db/tables/group_table.dart';
import 'package:game_tracker/data/db/tables/player_group_table.dart';
import 'package:game_tracker/data/dto/group.dart'; import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
part 'group_dao.g.dart'; part 'group_dao.g.dart';
@DriftAccessor(tables: [GroupTable, PlayerGroupTable]) @DriftAccessor(tables: [GroupTable])
class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin { class GroupDao extends DatabaseAccessor<AppDatabase> with _$GroupDaoMixin {
GroupDao(super.db); GroupDao(super.db);

View File

@@ -5,7 +5,4 @@ part of 'group_dao.dart';
// ignore_for_file: type=lint // ignore_for_file: type=lint
mixin _$GroupDaoMixin on DatabaseAccessor<AppDatabase> { mixin _$GroupDaoMixin on DatabaseAccessor<AppDatabase> {
$GroupTableTable get groupTable => attachedDatabase.groupTable; $GroupTableTable get groupTable => attachedDatabase.groupTable;
$PlayerTableTable get playerTable => attachedDatabase.playerTable;
$PlayerGroupTableTable get playerGroupTable =>
attachedDatabase.playerGroupTable;
} }

View File

@@ -0,0 +1,98 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/group_game_table.dart';
import 'package:game_tracker/data/dto/group.dart';
part 'group_game_dao.g.dart';
@DriftAccessor(tables: [GroupGameTable])
class GroupGameDao extends DatabaseAccessor<AppDatabase>
with _$GroupGameDaoMixin {
GroupGameDao(super.db);
/// Associates a group with a game by inserting a record into the
/// [GroupGameTable].
Future<void> addGroupToGame({
required String gameId,
required String groupId,
}) async {
if (await gameHasGroup(gameId: gameId)) {
throw Exception('Game already has a group');
}
await into(groupGameTable).insert(
GroupGameTableCompanion.insert(groupId: groupId, gameId: gameId),
mode: InsertMode.insertOrReplace,
);
}
/// Retrieves the [Group] associated with the given [gameId].
/// Returns `null` if no group is found.
Future<Group?> getGroupOfGame({required String gameId}) async {
final result = await (select(
groupGameTable,
)..where((g) => g.gameId.equals(gameId))).getSingleOrNull();
if (result == null) {
return null;
}
final group = await db.groupDao.getGroupById(groupId: result.groupId);
return group;
}
/// Checks if there is a group associated with the given [gameId].
/// Returns `true` if there is a group, otherwise `false`.
Future<bool> gameHasGroup({required String gameId}) async {
final count =
await (selectOnly(groupGameTable)
..where(groupGameTable.gameId.equals(gameId))
..addColumns([groupGameTable.groupId.count()]))
.map((row) => row.read(groupGameTable.groupId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Checks if a specific group is associated with a specific game.
/// Returns `true` if the group is in the game, otherwise `false`.
Future<bool> isGroupInGame({
required String gameId,
required String groupId,
}) async {
final count =
await (selectOnly(groupGameTable)
..where(
groupGameTable.gameId.equals(gameId) &
groupGameTable.groupId.equals(groupId),
)
..addColumns([groupGameTable.groupId.count()]))
.map((row) => row.read(groupGameTable.groupId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Removes the association of a group from a game based on [groupId] and
/// [gameId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> removeGroupFromGame({
required String gameId,
required String groupId,
}) async {
final query = delete(groupGameTable)
..where((g) => g.gameId.equals(gameId) & g.groupId.equals(groupId));
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Updates the group associated with a game to [newGroupId] based on
/// [gameId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> updateGroupOfGame({
required String gameId,
required String newGroupId,
}) async {
final updatedRows =
await (update(groupGameTable)..where((g) => g.gameId.equals(gameId)))
.write(GroupGameTableCompanion(groupId: Value(newGroupId)));
return updatedRows > 0;
}
}

View File

@@ -0,0 +1,10 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'group_game_dao.dart';
// ignore_for_file: type=lint
mixin _$GroupGameDaoMixin on DatabaseAccessor<AppDatabase> {
$GroupTableTable get groupTable => attachedDatabase.groupTable;
$GameTableTable get gameTable => attachedDatabase.gameTable;
$GroupGameTableTable get groupGameTable => attachedDatabase.groupGameTable;
}

View File

@@ -1,98 +0,0 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/group_match_table.dart';
import 'package:game_tracker/data/dto/group.dart';
part 'group_match_dao.g.dart';
@DriftAccessor(tables: [GroupMatchTable])
class GroupMatchDao extends DatabaseAccessor<AppDatabase>
with _$GroupMatchDaoMixin {
GroupMatchDao(super.db);
/// Associates a group with a match by inserting a record into the
/// [GroupMatchTable].
Future<void> addGroupToMatch({
required String matchId,
required String groupId,
}) async {
if (await matchHasGroup(matchId: matchId)) {
throw Exception('Match already has a group');
}
await into(groupMatchTable).insert(
GroupMatchTableCompanion.insert(groupId: groupId, matchId: matchId),
mode: InsertMode.insertOrIgnore,
);
}
/// Retrieves the [Group] associated with the given [matchId].
/// Returns `null` if no group is found.
Future<Group?> getGroupOfMatch({required String matchId}) async {
final result = await (select(
groupMatchTable,
)..where((g) => g.matchId.equals(matchId))).getSingleOrNull();
if (result == null) {
return null;
}
final group = await db.groupDao.getGroupById(groupId: result.groupId);
return group;
}
/// Checks if there is a group associated with the given [matchId].
/// Returns `true` if there is a group, otherwise `false`.
Future<bool> matchHasGroup({required String matchId}) async {
final count =
await (selectOnly(groupMatchTable)
..where(groupMatchTable.matchId.equals(matchId))
..addColumns([groupMatchTable.groupId.count()]))
.map((row) => row.read(groupMatchTable.groupId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Checks if a specific group is associated with a specific match.
/// Returns `true` if the group is in the match, otherwise `false`.
Future<bool> isGroupInMatch({
required String matchId,
required String groupId,
}) async {
final count =
await (selectOnly(groupMatchTable)
..where(
groupMatchTable.matchId.equals(matchId) &
groupMatchTable.groupId.equals(groupId),
)
..addColumns([groupMatchTable.groupId.count()]))
.map((row) => row.read(groupMatchTable.groupId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Removes the association of a group from a match based on [groupId] and
/// [matchId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> removeGroupFromMatch({
required String matchId,
required String groupId,
}) async {
final query = delete(groupMatchTable)
..where((g) => g.matchId.equals(matchId) & g.groupId.equals(groupId));
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Updates the group associated with a match to [newGroupId] based on
/// [matchId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> updateGroupOfMatch({
required String matchId,
required String newGroupId,
}) async {
final updatedRows =
await (update(groupMatchTable)..where((g) => g.matchId.equals(matchId)))
.write(GroupMatchTableCompanion(groupId: Value(newGroupId)));
return updatedRows > 0;
}
}

View File

@@ -1,10 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'group_match_dao.dart';
// ignore_for_file: type=lint
mixin _$GroupMatchDaoMixin on DatabaseAccessor<AppDatabase> {
$GroupTableTable get groupTable => attachedDatabase.groupTable;
$MatchTableTable get matchTable => attachedDatabase.matchTable;
$GroupMatchTableTable get groupMatchTable => attachedDatabase.groupMatchTable;
}

View File

@@ -1,322 +0,0 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/match_table.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart';
part 'match_dao.g.dart';
@DriftAccessor(tables: [MatchTable])
class MatchDao extends DatabaseAccessor<AppDatabase> with _$MatchDaoMixin {
MatchDao(super.db);
/// Retrieves all matches from the database.
Future<List<Match>> getAllMatches() async {
final query = select(matchTable);
final result = await query.get();
return Future.wait(
result.map((row) async {
final group = await db.groupMatchDao.getGroupOfMatch(matchId: row.id);
final players = await db.playerMatchDao.getPlayersOfMatch(
matchId: row.id,
);
final winner = row.winnerId != null
? await db.playerDao.getPlayerById(playerId: row.winnerId!)
: null;
return Match(
id: row.id,
name: row.name,
group: group,
players: players,
createdAt: row.createdAt,
winner: winner,
);
}),
);
}
/// Retrieves a [Match] by its [matchId].
Future<Match> getMatchById({required String matchId}) async {
final query = select(matchTable)..where((g) => g.id.equals(matchId));
final result = await query.getSingle();
List<Player>? players;
if (await db.playerMatchDao.matchHasPlayers(matchId: matchId)) {
players = await db.playerMatchDao.getPlayersOfMatch(matchId: matchId);
}
Group? group;
if (await db.groupMatchDao.matchHasGroup(matchId: matchId)) {
group = await db.groupMatchDao.getGroupOfMatch(matchId: matchId);
}
Player? winner;
if (result.winnerId != null) {
winner = await db.playerDao.getPlayerById(playerId: result.winnerId!);
}
return Match(
id: result.id,
name: result.name,
players: players,
group: group,
winner: winner,
createdAt: result.createdAt,
);
}
/// Adds a new [Match] to the database. Also adds players and group
/// associations. This method assumes that the players and groups added to
/// this match are already present in the database.
Future<void> addMatch({required Match match}) async {
await db.transaction(() async {
await into(matchTable).insert(
MatchTableCompanion.insert(
id: match.id,
name: match.name,
winnerId: Value(match.winner?.id),
createdAt: match.createdAt,
),
mode: InsertMode.insertOrReplace,
);
if (match.players != null) {
for (final p in match.players ?? []) {
await db.playerMatchDao.addPlayerToMatch(
matchId: match.id,
playerId: p.id,
);
}
}
if (match.group != null) {
await db.groupMatchDao.addGroupToMatch(
matchId: match.id,
groupId: match.group!.id,
);
}
});
}
/// Adds multiple [Match]s to the database in a batch operation.
/// Also adds associated players and groups if they exist.
/// If the [matches] list is empty, the method returns immediately.
/// This Method should only be used to import matches from a different device.
Future<void> addMatchAsList({required List<Match> matches}) async {
if (matches.isEmpty) return;
await db.transaction(() async {
// Add all matches in batch
await db.batch(
(b) => b.insertAll(
matchTable,
matches
.map(
(match) => MatchTableCompanion.insert(
id: match.id,
name: match.name,
createdAt: match.createdAt,
winnerId: Value(match.winner?.id),
),
)
.toList(),
mode: InsertMode.insertOrReplace,
),
);
// Add all groups of the matches in batch
await db.batch(
(b) => b.insertAll(
db.groupTable,
matches
.where((match) => match.group != null)
.map(
(matches) => GroupTableCompanion.insert(
id: matches.group!.id,
name: matches.group!.name,
createdAt: matches.group!.createdAt,
),
)
.toList(),
mode: InsertMode.insertOrReplace,
),
);
// Add all players of the matches in batch (unique)
final uniquePlayers = <String, Player>{};
for (final match in matches) {
if (match.players != null) {
for (final p in match.players!) {
uniquePlayers[p.id] = p;
}
}
// Also include members of groups
if (match.group != null) {
for (final m in match.group!.members) {
uniquePlayers[m.id] = m;
}
}
}
if (uniquePlayers.isNotEmpty) {
await db.batch(
(b) => b.insertAll(
db.playerTable,
uniquePlayers.values
.map(
(p) => PlayerTableCompanion.insert(
id: p.id,
name: p.name,
createdAt: p.createdAt,
),
)
.toList(),
mode: InsertMode.insertOrReplace,
),
);
}
// Add all player-match associations in batch
await db.batch((b) {
for (final match in matches) {
if (match.players != null) {
for (final p in match.players ?? []) {
b.insert(
db.playerMatchTable,
PlayerMatchTableCompanion.insert(
matchId: match.id,
playerId: p.id,
),
mode: InsertMode.insertOrIgnore,
);
}
}
}
});
// Add all player-group associations in batch
await db.batch((b) {
for (final match in matches) {
if (match.group != null) {
for (final m in match.group!.members) {
b.insert(
db.playerGroupTable,
PlayerGroupTableCompanion.insert(
playerId: m.id,
groupId: match.group!.id,
),
mode: InsertMode.insertOrIgnore,
);
}
}
}
});
// Add all group-match associations in batch
await db.batch((b) {
for (final match in matches) {
if (match.group != null) {
b.insert(
db.groupMatchTable,
GroupMatchTableCompanion.insert(
matchId: match.id,
groupId: match.group!.id,
),
mode: InsertMode.insertOrIgnore,
);
}
}
});
});
}
/// Deletes the match with the given [matchId] from the database.
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> deleteMatch({required String matchId}) async {
final query = delete(matchTable)..where((g) => g.id.equals(matchId));
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Retrieves the number of matches in the database.
Future<int> getMatchCount() async {
final count =
await (selectOnly(matchTable)..addColumns([matchTable.id.count()]))
.map((row) => row.read(matchTable.id.count()))
.getSingle();
return count ?? 0;
}
/// Checks if a match with the given [matchId] exists in the database.
/// Returns `true` if the match exists, otherwise `false`.
Future<bool> matchExists({required String matchId}) async {
final query = select(matchTable)..where((g) => g.id.equals(matchId));
final result = await query.getSingleOrNull();
return result != null;
}
/// Deletes all matches from the database.
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> deleteAllMatches() async {
final query = delete(matchTable);
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Sets the winner of the match with the given [matchId] to the player with
/// the given [winnerId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> setWinner({
required String matchId,
required String winnerId,
}) async {
final query = update(matchTable)..where((g) => g.id.equals(matchId));
final rowsAffected = await query.write(
MatchTableCompanion(winnerId: Value(winnerId)),
);
return rowsAffected > 0;
}
/// Retrieves the winner of the match with the given [matchId].
/// Returns the [Player] who won the match, or `null` if no winner is set.
Future<Player?> getWinner({required String matchId}) async {
final query = select(matchTable)..where((g) => g.id.equals(matchId));
final result = await query.getSingleOrNull();
if (result == null || result.winnerId == null) {
return null;
}
final winner = await db.playerDao.getPlayerById(playerId: result.winnerId!);
return winner;
}
/// Removes the winner of the match with the given [matchId].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> removeWinner({required String matchId}) async {
final query = update(matchTable)..where((g) => g.id.equals(matchId));
final rowsAffected = await query.write(
const MatchTableCompanion(winnerId: Value(null)),
);
return rowsAffected > 0;
}
/// Checks if the match with the given [matchId] has a winner set.
/// Returns `true` if a winner is set, otherwise `false`.
Future<bool> hasWinner({required String matchId}) async {
final query = select(matchTable)
..where((g) => g.id.equals(matchId) & g.winnerId.isNotNull());
final result = await query.getSingleOrNull();
return result != null;
}
/// Changes the title of the match with the given [matchId] to [newName].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> updateMatchName({
required String matchId,
required String newName,
}) async {
final query = update(matchTable)..where((g) => g.id.equals(matchId));
final rowsAffected = await query.write(
MatchTableCompanion(name: Value(newName)),
);
return rowsAffected > 0;
}
}

View File

@@ -1,8 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'match_dao.dart';
// ignore_for_file: type=lint
mixin _$MatchDaoMixin on DatabaseAccessor<AppDatabase> {
$MatchTableTable get matchTable => attachedDatabase.matchTable;
}

View File

@@ -0,0 +1,128 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/player_game_table.dart';
import 'package:game_tracker/data/dto/player.dart';
part 'player_game_dao.g.dart';
@DriftAccessor(tables: [PlayerGameTable])
class PlayerGameDao extends DatabaseAccessor<AppDatabase>
with _$PlayerGameDaoMixin {
PlayerGameDao(super.db);
/// Associates a player with a game by inserting a record into the
/// [PlayerGameTable].
Future<void> addPlayerToGame({
required String gameId,
required String playerId,
}) async {
await into(playerGameTable).insert(
PlayerGameTableCompanion.insert(playerId: playerId, gameId: gameId),
mode: InsertMode.insertOrReplace,
);
}
/// Retrieves a list of [Player]s associated with the given [gameId].
/// Returns null if no players are found.
Future<List<Player>?> getPlayersOfGame({required String gameId}) async {
final result = await (select(
playerGameTable,
)..where((p) => p.gameId.equals(gameId))).get();
if (result.isEmpty) return null;
final futures = result.map(
(row) => db.playerDao.getPlayerById(playerId: row.playerId),
);
final players = await Future.wait(futures);
return players;
}
/// Checks if there are any players associated with the given [gameId].
/// Returns `true` if there are players, otherwise `false`.
Future<bool> gameHasPlayers({required String gameId}) async {
final count =
await (selectOnly(playerGameTable)
..where(playerGameTable.gameId.equals(gameId))
..addColumns([playerGameTable.playerId.count()]))
.map((row) => row.read(playerGameTable.playerId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Checks if a specific player is associated with a specific game.
/// Returns `true` if the player is in the game, otherwise `false`.
Future<bool> isPlayerInGame({
required String gameId,
required String playerId,
}) async {
final count =
await (selectOnly(playerGameTable)
..where(playerGameTable.gameId.equals(gameId))
..where(playerGameTable.playerId.equals(playerId))
..addColumns([playerGameTable.playerId.count()]))
.map((row) => row.read(playerGameTable.playerId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Removes the association of a player with a game by deleting the record
/// from the [PlayerGameTable].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> removePlayerFromGame({
required String gameId,
required String playerId,
}) async {
final query = delete(playerGameTable)
..where((pg) => pg.gameId.equals(gameId))
..where((pg) => pg.playerId.equals(playerId));
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Updates the players associated with a game based on the provided
/// [newPlayer] list. It adds new players and removes players that are no
/// longer associated with the game.
Future<void> updatePlayersFromGame({
required String gameId,
required List<Player> newPlayer,
}) async {
final currentPlayers = await getPlayersOfGame(gameId: gameId);
// Create sets of player IDs for easy comparison
final currentPlayerIds = currentPlayers?.map((p) => p.id).toSet() ?? {};
final newPlayerIdsSet = newPlayer.map((p) => p.id).toSet();
// Determine players to add and remove
final playersToAdd = newPlayerIdsSet.difference(currentPlayerIds);
final playersToRemove = currentPlayerIds.difference(newPlayerIdsSet);
db.transaction(() async {
// Remove old players
if (playersToRemove.isNotEmpty) {
await (delete(playerGameTable)..where(
(pg) =>
pg.gameId.equals(gameId) &
pg.playerId.isIn(playersToRemove.toList()),
))
.go();
}
// Add new players
if (playersToAdd.isNotEmpty) {
final inserts = playersToAdd
.map(
(id) =>
PlayerGameTableCompanion.insert(playerId: id, gameId: gameId),
)
.toList();
await Future.wait(
inserts.map(
(c) => into(
playerGameTable,
).insert(c, mode: InsertMode.insertOrReplace),
),
);
}
});
}
}

View File

@@ -0,0 +1,10 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'player_game_dao.dart';
// ignore_for_file: type=lint
mixin _$PlayerGameDaoMixin on DatabaseAccessor<AppDatabase> {
$PlayerTableTable get playerTable => attachedDatabase.playerTable;
$GameTableTable get gameTable => attachedDatabase.gameTable;
$PlayerGameTableTable get playerGameTable => attachedDatabase.playerGameTable;
}

View File

@@ -1,12 +1,11 @@
import 'package:drift/drift.dart'; import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/player_group_table.dart'; import 'package:game_tracker/data/db/tables/player_group_table.dart';
import 'package:game_tracker/data/db/tables/player_table.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
part 'player_group_dao.g.dart'; part 'player_group_dao.g.dart';
@DriftAccessor(tables: [PlayerGroupTable, PlayerTable]) @DriftAccessor(tables: [PlayerGroupTable])
class PlayerGroupDao extends DatabaseAccessor<AppDatabase> class PlayerGroupDao extends DatabaseAccessor<AppDatabase>
with _$PlayerGroupDaoMixin { with _$PlayerGroupDaoMixin {
PlayerGroupDao(super.db); PlayerGroupDao(super.db);

View File

@@ -1,130 +0,0 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/db/tables/player_match_table.dart';
import 'package:game_tracker/data/dto/player.dart';
part 'player_match_dao.g.dart';
@DriftAccessor(tables: [PlayerMatchTable])
class PlayerMatchDao extends DatabaseAccessor<AppDatabase>
with _$PlayerMatchDaoMixin {
PlayerMatchDao(super.db);
/// Associates a player with a match by inserting a record into the
/// [PlayerMatchTable].
Future<void> addPlayerToMatch({
required String matchId,
required String playerId,
}) async {
await into(playerMatchTable).insert(
PlayerMatchTableCompanion.insert(playerId: playerId, matchId: matchId),
mode: InsertMode.insertOrIgnore,
);
}
/// Retrieves a list of [Player]s associated with the given [matchId].
/// Returns null if no players are found.
Future<List<Player>?> getPlayersOfMatch({required String matchId}) async {
final result = await (select(
playerMatchTable,
)..where((p) => p.matchId.equals(matchId))).get();
if (result.isEmpty) return null;
final futures = result.map(
(row) => db.playerDao.getPlayerById(playerId: row.playerId),
);
final players = await Future.wait(futures);
return players;
}
/// Checks if there are any players associated with the given [matchId].
/// Returns `true` if there are players, otherwise `false`.
Future<bool> matchHasPlayers({required String matchId}) async {
final count =
await (selectOnly(playerMatchTable)
..where(playerMatchTable.matchId.equals(matchId))
..addColumns([playerMatchTable.playerId.count()]))
.map((row) => row.read(playerMatchTable.playerId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Checks if a specific player is associated with a specific match.
/// Returns `true` if the player is in the match, otherwise `false`.
Future<bool> isPlayerInMatch({
required String matchId,
required String playerId,
}) async {
final count =
await (selectOnly(playerMatchTable)
..where(playerMatchTable.matchId.equals(matchId))
..where(playerMatchTable.playerId.equals(playerId))
..addColumns([playerMatchTable.playerId.count()]))
.map((row) => row.read(playerMatchTable.playerId.count()))
.getSingle();
return (count ?? 0) > 0;
}
/// Removes the association of a player with a match by deleting the record
/// from the [PlayerMatchTable].
/// Returns `true` if more than 0 rows were affected, otherwise `false`.
Future<bool> removePlayerFromMatch({
required String matchId,
required String playerId,
}) async {
final query = delete(playerMatchTable)
..where((pg) => pg.matchId.equals(matchId))
..where((pg) => pg.playerId.equals(playerId));
final rowsAffected = await query.go();
return rowsAffected > 0;
}
/// Updates the players associated with a match based on the provided
/// [newPlayer] list. It adds new players and removes players that are no
/// longer associated with the match.
Future<void> updatePlayersFromMatch({
required String matchId,
required List<Player> newPlayer,
}) async {
final currentPlayers = await getPlayersOfMatch(matchId: matchId);
// Create sets of player IDs for easy comparison
final currentPlayerIds = currentPlayers?.map((p) => p.id).toSet() ?? {};
final newPlayerIdsSet = newPlayer.map((p) => p.id).toSet();
// Determine players to add and remove
final playersToAdd = newPlayerIdsSet.difference(currentPlayerIds);
final playersToRemove = currentPlayerIds.difference(newPlayerIdsSet);
db.transaction(() async {
// Remove old players
if (playersToRemove.isNotEmpty) {
await (delete(playerMatchTable)..where(
(pg) =>
pg.matchId.equals(matchId) &
pg.playerId.isIn(playersToRemove.toList()),
))
.go();
}
// Add new players
if (playersToAdd.isNotEmpty) {
final inserts = playersToAdd
.map(
(id) => PlayerMatchTableCompanion.insert(
playerId: id,
matchId: matchId,
),
)
.toList();
await Future.wait(
inserts.map(
(c) => into(
playerMatchTable,
).insert(c, mode: InsertMode.insertOrIgnore),
),
);
}
});
}
}

View File

@@ -1,11 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'player_match_dao.dart';
// ignore_for_file: type=lint
mixin _$PlayerMatchDaoMixin on DatabaseAccessor<AppDatabase> {
$PlayerTableTable get playerTable => attachedDatabase.playerTable;
$MatchTableTable get matchTable => attachedDatabase.matchTable;
$PlayerMatchTableTable get playerMatchTable =>
attachedDatabase.playerMatchTable;
}

View File

@@ -1,16 +1,16 @@
import 'package:drift/drift.dart'; import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart'; import 'package:drift_flutter/drift_flutter.dart';
import 'package:game_tracker/data/dao/game_dao.dart';
import 'package:game_tracker/data/dao/group_dao.dart'; import 'package:game_tracker/data/dao/group_dao.dart';
import 'package:game_tracker/data/dao/group_match_dao.dart'; import 'package:game_tracker/data/dao/group_game_dao.dart';
import 'package:game_tracker/data/dao/match_dao.dart';
import 'package:game_tracker/data/dao/player_dao.dart'; import 'package:game_tracker/data/dao/player_dao.dart';
import 'package:game_tracker/data/dao/player_game_dao.dart';
import 'package:game_tracker/data/dao/player_group_dao.dart'; import 'package:game_tracker/data/dao/player_group_dao.dart';
import 'package:game_tracker/data/dao/player_match_dao.dart'; import 'package:game_tracker/data/db/tables/game_table.dart';
import 'package:game_tracker/data/db/tables/group_match_table.dart'; import 'package:game_tracker/data/db/tables/group_game_table.dart';
import 'package:game_tracker/data/db/tables/group_table.dart'; import 'package:game_tracker/data/db/tables/group_table.dart';
import 'package:game_tracker/data/db/tables/match_table.dart'; import 'package:game_tracker/data/db/tables/player_game_table.dart';
import 'package:game_tracker/data/db/tables/player_group_table.dart'; import 'package:game_tracker/data/db/tables/player_group_table.dart';
import 'package:game_tracker/data/db/tables/player_match_table.dart';
import 'package:game_tracker/data/db/tables/player_table.dart'; import 'package:game_tracker/data/db/tables/player_table.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
@@ -20,18 +20,18 @@ part 'database.g.dart';
tables: [ tables: [
PlayerTable, PlayerTable,
GroupTable, GroupTable,
MatchTable, GameTable,
PlayerGroupTable, PlayerGroupTable,
PlayerMatchTable, PlayerGameTable,
GroupMatchTable, GroupGameTable,
], ],
daos: [ daos: [
PlayerDao, PlayerDao,
GroupDao, GroupDao,
MatchDao, GameDao,
PlayerGroupDao, PlayerGroupDao,
PlayerMatchDao, PlayerGameDao,
GroupMatchDao, GroupGameDao,
], ],
) )
class AppDatabase extends _$AppDatabase { class AppDatabase extends _$AppDatabase {

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import 'package:drift/drift.dart'; import 'package:drift/drift.dart';
class MatchTable extends Table { class GameTable extends Table {
TextColumn get id => text()(); TextColumn get id => text()();
TextColumn get name => text()(); TextColumn get name => text()();
late final winnerId = text().nullable()(); late final winnerId = text().nullable()();

View File

@@ -0,0 +1,13 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/tables/game_table.dart';
import 'package:game_tracker/data/db/tables/group_table.dart';
class GroupGameTable extends Table {
TextColumn get groupId =>
text().references(GroupTable, #id, onDelete: KeyAction.cascade)();
TextColumn get gameId =>
text().references(GameTable, #id, onDelete: KeyAction.cascade)();
@override
Set<Column<Object>> get primaryKey => {groupId, gameId};
}

View File

@@ -1,13 +0,0 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/tables/group_table.dart';
import 'package:game_tracker/data/db/tables/match_table.dart';
class GroupMatchTable extends Table {
TextColumn get groupId =>
text().references(GroupTable, #id, onDelete: KeyAction.cascade)();
TextColumn get matchId =>
text().references(MatchTable, #id, onDelete: KeyAction.cascade)();
@override
Set<Column<Object>> get primaryKey => {groupId, matchId};
}

View File

@@ -0,0 +1,13 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/tables/game_table.dart';
import 'package:game_tracker/data/db/tables/player_table.dart';
class PlayerGameTable extends Table {
TextColumn get playerId =>
text().references(PlayerTable, #id, onDelete: KeyAction.cascade)();
TextColumn get gameId =>
text().references(GameTable, #id, onDelete: KeyAction.cascade)();
@override
Set<Column<Object>> get primaryKey => {playerId, gameId};
}

View File

@@ -1,13 +0,0 @@
import 'package:drift/drift.dart';
import 'package:game_tracker/data/db/tables/match_table.dart';
import 'package:game_tracker/data/db/tables/player_table.dart';
class PlayerMatchTable extends Table {
TextColumn get playerId =>
text().references(PlayerTable, #id, onDelete: KeyAction.cascade)();
TextColumn get matchId =>
text().references(MatchTable, #id, onDelete: KeyAction.cascade)();
@override
Set<Column<Object>> get primaryKey => {playerId, matchId};
}

View File

@@ -3,7 +3,7 @@ import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
class Match { class Game {
final String id; final String id;
final DateTime createdAt; final DateTime createdAt;
final String name; final String name;
@@ -11,7 +11,7 @@ class Match {
final Group? group; final Group? group;
final Player? winner; final Player? winner;
Match({ Game({
String? id, String? id,
DateTime? createdAt, DateTime? createdAt,
required this.name, required this.name,
@@ -23,11 +23,11 @@ class Match {
@override @override
String toString() { String toString() {
return 'Match{\n\tid: $id,\n\tname: $name,\n\tplayers: $players,\n\tgroup: $group,\n\twinner: $winner\n}'; return 'Game{\n\tid: $id,\n\tname: $name,\n\tplayers: $players,\n\tgroup: $group,\n\twinner: $winner\n}';
} }
/// Creates a Match instance from a JSON object. /// Creates a Game instance from a JSON object.
Match.fromJson(Map<String, dynamic> json) Game.fromJson(Map<String, dynamic> json)
: id = json['id'], : id = json['id'],
name = json['name'], name = json['name'],
createdAt = DateTime.parse(json['createdAt']), createdAt = DateTime.parse(json['createdAt']),
@@ -39,7 +39,7 @@ class Match {
group = json['group'] != null ? Group.fromJson(json['group']) : null, group = json['group'] != null ? Group.fromJson(json['group']) : null,
winner = json['winner'] != null ? Player.fromJson(json['winner']) : null; winner = json['winner'] != null ? Player.fromJson(json['winner']) : null;
/// Converts the Match instance to a JSON object. /// Converts the Game instance to a JSON object.
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
'id': id, 'id': id,
'createdAt': createdAt.toIso8601String(), 'createdAt': createdAt.toIso8601String(),

View File

@@ -1,84 +0,0 @@
{
"@@locale": "de",
"choose_group": "Gruppe wählen",
"create_new_match": "Neues Match erstellen",
"choose_ruleset": "Regelwerk wählen",
"choose_game": "Spiel wählen",
"select_winner": "Gewinner wählen:",
"no_recent_matches_available": "Keine letzten Matches verfügbar",
"no_second_match_available": "Kein zweites Match verfügbar",
"delete_all_data": "Alle Daten löschen?",
"cancel": "Abbrechen",
"delete": "Löschen",
"create_new_group": "Neue Gruppe erstellen",
"error_while_creating_group_please_try_again": "Fehler beim Erstellen der Gruppe, bitte erneut versuchen",
"selected_players": "Ausgewählte Spieler: {count}",
"no_players_selected": "Keine Spieler ausgewählt",
"all_players": "Alle Spieler:",
"successfully_added_player": "Spieler {playerName} erfolgreich hinzugefügt.",
"could_not_add_player": "Spieler {playerName} konnte nicht hinzugefügt werden.",
"winner": "Gewinner: {winnerName}",
"players": "Spieler",
"player_name": "Spielername",
"no_data_available": "Keine Daten verfügbar.",
"matches": "Matches",
"groups": "Gruppen",
"recent_matches": "Letzte Matches",
"quick_create": "Schnellzugriff",
"winner_label": "Gewinner",
"ruleset_label": "Regelwerk",
"match_in_progress": "Match läuft...",
"menu": "Menü",
"settings": "Einstellungen",
"export_data": "Daten exportieren",
"import_data": "Daten importieren",
"this_cannot_be_undone": "Dies kann nicht rückgängig gemacht werden",
"data_successfully_deleted": "Daten erfolgreich gelöscht",
"data_successfully_imported": "Daten erfolgreich importiert",
"invalid_schema": "Ungültiges Schema",
"error_reading_file": "Fehler beim Lesen der Datei",
"import_canceled": "Import abgebrochen",
"format_exception": "Formatfehler (siehe Konsole)",
"unknown_exception": "Unbekannter Fehler (siehe Konsole)",
"data_successfully_exported": "Daten erfolgreich exportiert",
"export_canceled": "Export abgebrochen",
"undo": "Rückgängig",
"wins": "Siege",
"winrate": "Siegquote",
"amount_of_matches": "Anzahl der Matches",
"info": "Info",
"no_groups_created_yet": "Noch keine Gruppen erstellt",
"create_group": "Gruppe erstellen",
"group_name": "Gruppenname",
"no_matches_created_yet": "Noch keine Matches erstellt",
"create_game": "Match erstellen",
"match_name": "Matchname",
"game": "Spiel",
"ruleset": "Regelwerk",
"group": "Gruppe",
"none": "Keine",
"create_match": "Match erstellen",
"search_for_players": "Nach Spielern suchen",
"search_for_groups": "Nach Gruppen suchen",
"no_players_created_yet": "Noch keine Spieler erstellt",
"all_players_selected": "Alle Spieler ausgewählt",
"no_players_found_with_that_name": "Keine Spieler mit diesem Namen gefunden",
"today_at": "Heute um {time}",
"yesterday_at": "Gestern um {time}",
"days_ago": "vor {count} Tagen",
"home": "Startseite",
"statistics": "Statistiken",
"stats": "Statistiken",
"players_count": "{count} Spieler",
"you_have_no_groups_created_yet": "Du hast noch keine Gruppen erstellt",
"there_is_no_group_matching_your_search": "Es gibt keine Gruppe, die deiner Suche entspricht",
"game_name": "Spielname",
"ruleset_single_winner_desc": "Genau ein Gewinner wird gewählt; Unentschieden werden durch einen vordefinierten Tie-Breaker aufgelöst.",
"ruleset_single_loser_desc": "Genau ein Verlierer wird bestimmt; der letzte Platz erhält die Strafe oder Konsequenz.",
"ruleset_most_points_desc": "Traditionelles Regelwerk: Der Spieler mit den meisten Punkten gewinnt.",
"ruleset_least_points_desc": "Umgekehrte Wertung: Der Spieler mit den wenigsten Punkten gewinnt.",
"single_winner": "Ein Gewinner",
"single_loser": "Ein Verlierer",
"most_points": "Höchste Punkte",
"least_points": "Niedrigste Punkte"
}

View File

@@ -1,357 +0,0 @@
{
"@@locale": "en",
"choose_group": "Choose Group",
"@choose_group": {
"description": "Label for choosing a group"
},
"create_new_match": "Create new match",
"@create_new_match": {
"description": "Button text to create a new match"
},
"choose_ruleset": "Choose Ruleset",
"@choose_ruleset": {
"description": "Label for choosing a ruleset"
},
"choose_game": "Choose Game",
"@choose_game": {
"description": "Label for choosing a game"
},
"select_winner": "Select Winner:",
"@select_winner": {
"description": "Label to select the winner"
},
"no_recent_matches_available": "No recent matches available",
"@no_recent_matches_available": {
"description": "Message when no recent matches exist"
},
"no_second_match_available": "No second match available",
"@no_second_matcb_available": {
"description": "Message when no second match exists"
},
"delete_all_data": "Delete all data?",
"@delete_all_data": {
"description": "Confirmation dialog for deleting all data"
},
"cancel": "Cancel",
"@cancel": {
"description": "Cancel button text"
},
"delete": "Delete",
"@delete": {
"description": "Delete button text"
},
"create_new_group": "Create new group",
"@create_new_group": {
"description": "Button text to create a new group"
},
"error_while_creating_group_please_try_again": "Error while creating group, please try again",
"@error_while_creating_group_please_try_again": {
"description": "Error message when group creation fails"
},
"selected_players": "Selected players: {count}",
"@selected_players": {
"description": "Shows the number of selected players",
"placeholders": {
"count": {
"type": "int",
"format": "compact"
}
}
},
"no_players_selected": "No players selected",
"@no_players_selected": {
"description": "Message when no players are selected"
},
"all_players": "All players:",
"@all_players": {
"description": "Label for all players list"
},
"successfully_added_player": "Successfully added player {playerName}.",
"@successfully_added_player": {
"description": "Success message when adding a player",
"placeholders": {
"playerName": {
"type": "String",
"example": "John"
}
}
},
"could_not_add_player": "Could not add player {playerName}.",
"@could_not_add_player": {
"description": "Error message when adding a player fails",
"placeholders": {
"playerName": {
"type": "String",
"example": "John"
}
}
},
"winner": "Winner: {winnerName}",
"@winner": {
"description": "Shows the winner's name",
"placeholders": {
"winnerName": {
"type": "String",
"example": "John"
}
}
},
"players": "Players",
"@players": {
"description": "Players label"
},
"no_data_available": "No data available.",
"@no_data_available": {
"description": "Message when no data is available"
},
"matches": "Matches",
"@matches": {
"description": "Label for matches"
},
"groups": "Groups",
"@groups": {
"description": "Label for groups"
},
"recent_matches": "Recent Matches",
"@recent_matches": {
"description": "Title for recent matches section"
},
"quick_create": "Quick Create",
"@quick_create": {
"description": "Title for quick create section"
},
"winner_label": "Winner",
"@winner_label": {
"description": "Label for winner field"
},
"ruleset_label": "Ruleset",
"@ruleset_label": {
"description": "Label for ruleset field"
},
"match_in_progress": "Match in progress...",
"@match_in_progress": {
"description": "Message when match is in progress"
},
"menu": "Menu",
"@menu": {
"description": "Menu label"
},
"settings": "Settings",
"@settings": {
"description": "Settings label"
},
"export_data": "Export data",
"@export_data": {
"description": "Export data menu item"
},
"import_data": "Import data",
"@import_data": {
"description": "Import data menu item"
},
"this_cannot_be_undone": "This can't be undone",
"@this_cannot_be_undone": {
"description": "Warning message for irreversible actions"
},
"data_successfully_deleted": "Data successfully deleted",
"@data_successfully_deleted": {
"description": "Success message after deleting data"
},
"data_successfully_imported": "Data successfully imported",
"@data_successfully_imported": {
"description": "Success message after importing data"
},
"invalid_schema": "Invalid Schema",
"@invalid_schema": {
"description": "Error message for invalid schema"
},
"error_reading_file": "Error reading file",
"@error_reading_file": {
"description": "Error message when file cannot be read"
},
"import_canceled": "Import canceled",
"@import_canceled": {
"description": "Message when import is canceled"
},
"format_exception": "Format Exception (see console)",
"@format_exception": {
"description": "Error message for format exceptions"
},
"unknown_exception": "Unknown Exception (see console)",
"@unknown_exception": {
"description": "Error message for unknown exceptions"
},
"data_successfully_exported": "Data successfully exported",
"@data_successfully_exported": {
"description": "Success message after exporting data"
},
"export_canceled": "Export canceled",
"@export_canceled": {
"description": "Message when export is canceled"
},
"undo": "Undo",
"@undo": {
"description": "Undo button text"
},
"wins": "Wins",
"@wins": {
"description": "Label for wins statistic"
},
"winrate": "Winrate",
"@winrate": {
"description": "Label for winrate statistic"
},
"amount_of_matches": "Amount of Matches",
"@amount_of_matches": {
"description": "Label for amount of matches statistic"
},
"info": "Info",
"@info": {
"description": "Info label"
},
"no_groups_created_yet": "No groups created yet",
"@no_groups_created_yet": {
"description": "Message when no groups exist"
},
"no_players_created_yet": "No players created yet",
"@no_players_created_yet": {
"description": "Message when no players exist"
},
"create_group": "Create Group",
"@create_group": {
"description": "Button text to create a group"
},
"group_name": "Group name",
"@group_name": {
"description": "Placeholder for group name input"
},
"player_name": "Player name",
"@player_name": {
"description": "Placeholder for player name input"
},
"no_matches_created_yet": "No matches created yet",
"@no_matches_created_yet": {
"description": "Message when no matches exist"
},
"match_name": "Match name",
"@match_name": {
"description": "Placeholder for match name input"
},
"game": "Game",
"@game": {
"description": "Game label"
},
"ruleset": "Ruleset",
"@ruleset": {
"description": "Ruleset label"
},
"group": "Group",
"@group": {
"description": "Group label"
},
"none": "None",
"@none": {
"description": "None option label"
},
"create_match": "Create match",
"@create_match": {
"description": "Button text to create a match"
},
"no_players_found_with_that_name": "No players found with that name",
"@no_players_found_with_that_name": {
"description": "Message when search returns no results"
},
"all_players_selected": "All players selected",
"@all_players_selected": {
"description": "Message when all players are added to selection"
},
"today_at": "Today at {time}",
"@today_at": {
"description": "Date format for today",
"placeholders": {
"time": {
"type": "String",
"example": "14:30"
}
}
},
"yesterday_at": "Yesterday at {time}",
"@yesterday_at": {
"description": "Date format for yesterday",
"placeholders": {
"time": {
"type": "String",
"example": "14:30"
}
}
},
"days_ago": "{count} days ago",
"@days_ago": {
"description": "Date format for days ago",
"placeholders": {
"count": {
"type": "int"
}
}
},
"home": "Home",
"@home": {
"description": "Home tab label"
},
"statistics": "Statistics",
"@statistics": {
"description": "Statistics tab label"
},
"stats": "Stats",
"@stats": {
"description": "Stats tab label (short)"
},
"players_count": "{count} Players",
"@players_count": {
"description": "Shows the number of players",
"placeholders": {
"count": {
"type": "int"
}
}
},
"there_is_no_group_matching_your_search": "There is no group matching your search",
"@there_is_no_group_matching_your_search": {
"description": "Message when search returns no groups"
},
"game_name": "Game Name",
"@game_name": {
"description": "Placeholder for game name search"
},
"ruleset_single_winner_desc": "Exactly one winner is chosen; ties are resolved by a predefined tiebreaker.",
"@ruleset_single_winner_desc": {
"description": "Description for single winner ruleset"
},
"ruleset_single_loser_desc": "Exactly one loser is determined; last place receives the penalty or consequence.",
"@ruleset_single_loser_desc": {
"description": "Description for single loser ruleset"
},
"ruleset_most_points_desc": "Traditional ruleset: the player with the most points wins.",
"@ruleset_most_points_desc": {
"description": "Description for most points ruleset"
},
"ruleset_least_points_desc": "Inverse scoring: the player with the fewest points wins.",
"@ruleset_least_points_desc": {
"description": "Description for least points ruleset"
},
"single_winner": "Single Winner",
"@single_winner": {
"description": "Title for single winner ruleset"
},
"single_loser": "Single Loser",
"@single_loser": {
"description": "Title for single loser ruleset"
},
"most_points": "Most Points",
"@most_points": {
"description": "Title for most points ruleset"
},
"least_points": "Least Points",
"@least_points": {
"description": "Title for least points ruleset"
}
}

View File

@@ -1,7 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/views/main_menu/custom_navigation_bar.dart'; import 'package:game_tracker/presentation/views/main_menu/custom_navigation_bar.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -21,8 +20,6 @@ class GameTracker extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
title: 'Game Tracker', title: 'Game Tracker',
darkTheme: ThemeData.dark(), darkTheme: ThemeData.dark(),

View File

@@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/presentation/widgets/tiles/group_tile.dart';
class ChooseGroupView extends StatefulWidget {
final List<Group> groups;
final int initialGroupIndex;
const ChooseGroupView({
super.key,
required this.groups,
required this.initialGroupIndex,
});
@override
State<ChooseGroupView> createState() => _ChooseGroupViewState();
}
class _ChooseGroupViewState extends State<ChooseGroupView> {
late int selectedGroupIndex;
@override
void initState() {
selectedGroupIndex = widget.initialGroupIndex;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
title: const Text(
'Choose Group',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: widget.groups.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
selectedGroupIndex = index;
});
Future.delayed(const Duration(milliseconds: 500), () {
if (!context.mounted) return;
Navigator.of(context).pop(widget.groups[index]);
});
},
child: GroupTile(
group: widget.groups[index],
isHighlighted: selectedGroupIndex == index,
),
);
},
),
);
}
}

View File

@@ -0,0 +1,120 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/presentation/widgets/tiles/ruleset_list_tile.dart';
class ChooseRulesetView extends StatefulWidget {
final List<(Ruleset, String, String)> rulesets;
final int initialRulesetIndex;
const ChooseRulesetView({
super.key,
required this.rulesets,
required this.initialRulesetIndex,
});
@override
State<ChooseRulesetView> createState() => _ChooseRulesetViewState();
}
class _ChooseRulesetViewState extends State<ChooseRulesetView> {
late int selectedRulesetIndex;
@override
void initState() {
selectedRulesetIndex = widget.initialRulesetIndex;
super.initState();
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
initialIndex: 0,
child: Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
title: const Text(
'Choose Ruleset',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Column(
children: [
Container(
color: CustomTheme.backgroundColor,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: TabBar(
padding: const EdgeInsets.symmetric(horizontal: 5),
// Label Settings
labelStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
labelColor: Colors.white,
unselectedLabelStyle: const TextStyle(fontSize: 14),
unselectedLabelColor: Colors.white70,
// Indicator Settings
indicator: CustomTheme.standardBoxDecoration,
indicatorSize: TabBarIndicatorSize.tab,
indicatorWeight: 1,
indicatorPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 0,
),
// Divider Settings
dividerHeight: 0,
tabs: const [
Tab(text: 'Rulesets'),
Tab(text: 'Gametypes'),
],
),
),
const Divider(
indent: 30,
endIndent: 30,
thickness: 3,
radius: BorderRadius.all(Radius.circular(12)),
),
Expanded(
child: TabBarView(
children: [
ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: widget.rulesets.length,
itemBuilder: (BuildContext context, int index) {
return RulesetListTile(
onPressed: () async {
setState(() {
selectedRulesetIndex = index;
});
Future.delayed(const Duration(milliseconds: 500), () {
if (!context.mounted) return;
Navigator.of(
context,
).pop(widget.rulesets[index].$1);
});
},
title: widget.rulesets[index].$2,
description: widget.rulesets[index].$3,
isHighlighted: selectedRulesetIndex == index,
);
},
),
const Center(
child: Text(
'No gametypes available',
style: TextStyle(color: Colors.white70),
),
),
],
),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,232 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/presentation/views/main_menu/create_game/choose_group_view.dart';
import 'package:game_tracker/presentation/views/main_menu/create_game/choose_ruleset_view.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/player_selection.dart';
import 'package:game_tracker/presentation/widgets/text_input/text_input_field.dart';
import 'package:game_tracker/presentation/widgets/tiles/choose_tile.dart';
import 'package:provider/provider.dart';
class CreateGameView extends StatefulWidget {
const CreateGameView({super.key});
@override
State<CreateGameView> createState() => _CreateGameViewState();
}
class _CreateGameViewState extends State<CreateGameView> {
/// Reference to the app database
late final AppDatabase db;
/// Futures to load all groups and players from the database
late Future<List<Group>> _allGroupsFuture;
/// Future to load all players from the database
late Future<List<Player>> _allPlayersFuture;
/// Controller for the game name input field
final TextEditingController _gameNameController = TextEditingController();
/// List of all groups from the database
List<Group> groupsList = [];
/// List of all players from the database
List<Player> playerList = [];
/// The currently selected group
Group? selectedGroup;
/// The index of the currently selected group in [groupsList] to mark it in
/// the [ChooseGroupView]
int selectedGroupIndex = -1;
/// The currently selected ruleset
Ruleset? selectedRuleset;
/// The index of the currently selected ruleset in [rulesets] to mark it in
/// the [ChooseRulesetView]
int selectedRulesetIndex = -1;
/// The currently selected players
List<Player>? selectedPlayers;
/// List of available rulesets with their display names and descriptions
/// as tuples of (Ruleset, String, String)
List<(Ruleset, String, String)> rulesets = [
(
Ruleset.singleWinner,
'Single Winner',
'Exactly one winner is chosen; ties are resolved by a predefined tiebreaker.',
),
(
Ruleset.singleLoser,
'Single Loser',
'Exactly one loser is determined; last place receives the penalty or consequence.',
),
(
Ruleset.mostPoints,
'Most Points',
'Traditional ruleset: the player with the most points wins.',
),
(
Ruleset.lastPoints,
'Least Points',
'Inverse scoring: the player with the fewest points wins.',
),
];
@override
void initState() {
super.initState();
db = Provider.of<AppDatabase>(context, listen: false);
_allGroupsFuture = db.groupDao.getAllGroups();
_allPlayersFuture = db.playerDao.getAllPlayers();
Future.wait([_allGroupsFuture, _allPlayersFuture]).then((result) async {
groupsList = result[0] as List<Group>;
playerList = result[1] as List<Player>;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
title: const Text(
'Create new game',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: TextInputField(
controller: _gameNameController,
hintText: 'Game name',
onChanged: (value) {
setState(() {});
},
),
),
ChooseTile(
title: 'Ruleset',
trailingText: selectedRuleset == null
? 'None'
: translateRulesetToString(selectedRuleset!),
onPressed: () async {
selectedRuleset = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChooseRulesetView(
rulesets: rulesets,
initialRulesetIndex: selectedRulesetIndex,
),
),
);
selectedRulesetIndex = rulesets.indexWhere(
(r) => r.$1 == selectedRuleset,
);
setState(() {});
},
),
ChooseTile(
title: 'Group',
trailingText: selectedGroup == null
? 'None'
: selectedGroup!.name,
onPressed: () async {
selectedGroup = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChooseGroupView(
groups: groupsList,
initialGroupIndex: selectedGroupIndex,
),
),
);
selectedGroupIndex = groupsList.indexWhere(
(g) => g.id == selectedGroup?.id,
);
setState(() {});
},
),
Expanded(
child: PlayerSelection(
key: ValueKey(selectedGroup?.id ?? 'no_group'),
initialPlayers: selectedGroup == null
? playerList
: playerList
.where(
(p) => !selectedGroup!.members.any(
(m) => m.id == p.id,
),
)
.toList(),
onChanged: (value) {
setState(() {
selectedPlayers = value;
});
},
),
),
CustomWidthButton(
text: 'Create game',
sizeRelativeToWidth: 0.95,
buttonType: ButtonType.primary,
onPressed: _enableCreateGameButton()
? () async {
Game game = Game(
name: _gameNameController.text.trim(),
createdAt: DateTime.now(),
group: selectedGroup!,
players: selectedPlayers,
);
// TODO: Replace with navigation to GameResultView()
print('Created game: $game');
Navigator.pop(context);
}
: null,
),
const SizedBox(height: 20),
],
),
),
);
}
/// Translates a [Ruleset] enum value to its corresponding string representation.
String translateRulesetToString(Ruleset ruleset) {
switch (ruleset) {
case Ruleset.singleWinner:
return 'Single Winner';
case Ruleset.singleLoser:
return 'Single Loser';
case Ruleset.mostPoints:
return 'Most Points';
case Ruleset.lastPoints:
return 'Least Points';
}
}
/// Determines whether the "Create Game" button should be enabled based on
/// the current state of the input fields.
bool _enableCreateGameButton() {
return _gameNameController.text.isNotEmpty &&
(selectedGroup != null ||
(selectedPlayers != null && selectedPlayers!.isNotEmpty)) &&
selectedRuleset != null;
}
}

View File

@@ -4,7 +4,6 @@ import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/group.dart'; import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart'; import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/player_selection.dart'; import 'package:game_tracker/presentation/widgets/player_selection.dart';
import 'package:game_tracker/presentation/widgets/text_input/text_input_field.dart'; import 'package:game_tracker/presentation/widgets/text_input/text_input_field.dart';
@@ -44,8 +43,8 @@ class _CreateGroupViewState extends State<CreateGroupView> {
appBar: AppBar( appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor, backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0, scrolledUnderElevation: 0,
title: Text( title: const Text(
AppLocalizations.of(context)!.create_new_group, 'Create new group',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
), ),
centerTitle: true, centerTitle: true,
@@ -58,7 +57,7 @@ class _CreateGroupViewState extends State<CreateGroupView> {
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: TextInputField( child: TextInputField(
controller: _groupNameController, controller: _groupNameController,
hintText: AppLocalizations.of(context)!.group_name, hintText: 'Group name',
onChanged: (value) { onChanged: (value) {
setState(() {}); setState(() {});
}, },
@@ -67,19 +66,16 @@ class _CreateGroupViewState extends State<CreateGroupView> {
Expanded( Expanded(
child: PlayerSelection( child: PlayerSelection(
onChanged: (value) { onChanged: (value) {
setState(() { selectedPlayers = [...value];
selectedPlayers = [...value];
});
}, },
), ),
), ),
CustomWidthButton( CustomWidthButton(
text: AppLocalizations.of(context)!.create_group, text: 'Create group',
sizeRelativeToWidth: 0.95, sizeRelativeToWidth: 0.95,
buttonType: ButtonType.primary, buttonType: ButtonType.primary,
onPressed: onPressed:
(_groupNameController.text.isEmpty || (_groupNameController.text.isEmpty || selectedPlayers.isEmpty)
(selectedPlayers.length < 2))
? null ? null
: () async { : () async {
bool success = await db.groupDao.addGroup( bool success = await db.groupDao.addGroup(
@@ -95,12 +91,10 @@ class _CreateGroupViewState extends State<CreateGroupView> {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
backgroundColor: CustomTheme.boxColor, backgroundColor: CustomTheme.boxColor,
content: Center( content: const Center(
child: Text( child: Text(
AppLocalizations.of( 'Error while creating group, please try again',
context, style: TextStyle(color: Colors.white),
)!.error_while_creating_group_please_try_again,
style: const TextStyle(color: Colors.white),
), ),
), ),
), ),

View File

@@ -1,9 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart'; import 'package:game_tracker/presentation/views/main_menu/game_history_view.dart';
import 'package:game_tracker/presentation/views/main_menu/group_view/groups_view.dart'; import 'package:game_tracker/presentation/views/main_menu/groups_view.dart';
import 'package:game_tracker/presentation/views/main_menu/home_view.dart'; import 'package:game_tracker/presentation/views/main_menu/home_view.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/match_view.dart';
import 'package:game_tracker/presentation/views/main_menu/settings_view.dart'; import 'package:game_tracker/presentation/views/main_menu/settings_view.dart';
import 'package:game_tracker/presentation/views/main_menu/statistics_view.dart'; import 'package:game_tracker/presentation/views/main_menu/statistics_view.dart';
import 'package:game_tracker/presentation/widgets/navbar_item.dart'; import 'package:game_tracker/presentation/widgets/navbar_item.dart';
@@ -31,8 +30,8 @@ class _CustomNavigationBarState extends State<CustomNavigationBar>
final List<Widget> tabs = [ final List<Widget> tabs = [
KeyedSubtree(key: ValueKey('home_$tabKeyCount'), child: const HomeView()), KeyedSubtree(key: ValueKey('home_$tabKeyCount'), child: const HomeView()),
KeyedSubtree( KeyedSubtree(
key: ValueKey('matches_$tabKeyCount'), key: ValueKey('games_$tabKeyCount'),
child: const MatchView(), child: const GameHistoryView(),
), ),
KeyedSubtree( KeyedSubtree(
key: ValueKey('groups_$tabKeyCount'), key: ValueKey('groups_$tabKeyCount'),
@@ -90,28 +89,28 @@ class _CustomNavigationBarState extends State<CustomNavigationBar>
index: 0, index: 0,
isSelected: currentIndex == 0, isSelected: currentIndex == 0,
icon: Icons.home_rounded, icon: Icons.home_rounded,
label: AppLocalizations.of(context)!.home, label: 'Home',
onTabTapped: onTabTapped, onTabTapped: onTabTapped,
), ),
NavbarItem( NavbarItem(
index: 1, index: 1,
isSelected: currentIndex == 1, isSelected: currentIndex == 1,
icon: Icons.gamepad_rounded, icon: Icons.gamepad_rounded,
label: AppLocalizations.of(context)!.matches, label: 'Games',
onTabTapped: onTabTapped, onTabTapped: onTabTapped,
), ),
NavbarItem( NavbarItem(
index: 2, index: 2,
isSelected: currentIndex == 2, isSelected: currentIndex == 2,
icon: Icons.group_rounded, icon: Icons.group_rounded,
label: AppLocalizations.of(context)!.groups, label: 'Groups',
onTabTapped: onTabTapped, onTabTapped: onTabTapped,
), ),
NavbarItem( NavbarItem(
index: 3, index: 3,
isSelected: currentIndex == 3, isSelected: currentIndex == 3,
icon: Icons.bar_chart_rounded, icon: Icons.bar_chart_rounded,
label: AppLocalizations.of(context)!.statistics, label: 'Stats',
onTabTapped: onTabTapped, onTabTapped: onTabTapped,
), ),
], ],
@@ -132,13 +131,13 @@ class _CustomNavigationBarState extends State<CustomNavigationBar>
String _currentTabTitle() { String _currentTabTitle() {
switch (currentIndex) { switch (currentIndex) {
case 0: case 0:
return AppLocalizations.of(context)!.home; return 'Home';
case 1: case 1:
return AppLocalizations.of(context)!.matches; return 'Game History';
case 2: case 2:
return AppLocalizations.of(context)!.groups; return 'Groups';
case 3: case 3:
return AppLocalizations.of(context)!.statistics; return 'Statistics';
default: default:
return ''; return '';
} }

View File

@@ -0,0 +1,150 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/presentation/views/main_menu/create_group_view.dart';
import 'package:game_tracker/presentation/views/main_menu/game_result_view.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/tiles/game_history_tile.dart';
import 'package:game_tracker/presentation/widgets/top_centered_message.dart';
import 'package:provider/provider.dart';
class GameHistoryView extends StatefulWidget {
const GameHistoryView({super.key});
@override
State<GameHistoryView> createState() => _GameHistoryViewState();
}
class _GameHistoryViewState extends State<GameHistoryView> {
late Future<List<Game>> _gameListFuture;
late final AppDatabase db;
late final List<Game> skeletonData = List.filled(
4,
Game(
name: 'Skeleton Game',
group: Group(
name: 'Skeleton Group',
members: [
Player(name: 'Player 1'),
Player(name: 'Player 2'),
Player(name: 'Player 3'),
Player(name: 'Long Name Player 4'),
Player(name: 'Player 5'),
],
),
winner: Player(name: 'Skeleton Player 1'),
players: [Player(name: 'Skeleton Player 6')],
),
);
@override
void initState() {
super.initState();
db = Provider.of<AppDatabase>(context, listen: false);
_gameListFuture = Future.delayed(
const Duration(milliseconds: 250),
() => db.gameDao.getAllGames(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
body: Stack(
alignment: Alignment.center,
children: [
FutureBuilder<List<Game>>(
future: _gameListFuture,
builder:
(BuildContext context, AsyncSnapshot<List<Game>> snapshot) {
if (snapshot.hasError) {
return const Center(
child: TopCenteredMessage(
icon: Icons.report,
title: 'Error',
message: 'Game data could not be loaded',
),
);
}
if (snapshot.connectionState == ConnectionState.done &&
(!snapshot.hasData || snapshot.data!.isEmpty)) {
return const Center(
child: TopCenteredMessage(
icon: Icons.report,
title: 'Info',
message: 'No games created yet',
),
);
}
final bool isLoading =
snapshot.connectionState == ConnectionState.waiting;
final List<Game> games =
(isLoading ? skeletonData : (snapshot.data ?? [])
..sort(
(a, b) => b.createdAt.compareTo(a.createdAt),
))
.toList();
return AppSkeleton(
enabled: isLoading,
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: games.length + 1,
itemBuilder: (BuildContext context, int index) {
if (index == games.length) {
return SizedBox(
height: MediaQuery.paddingOf(context).bottom - 80,
);
}
return GameHistoryTile(
onTap: () async {
await Navigator.push(
context,
CupertinoPageRoute(
fullscreenDialog: true,
builder: (context) =>
GameResultView(game: games[index]),
),
);
setState(() {
_gameListFuture = db.gameDao.getAllGames();
});
},
game: games[index],
);
},
),
);
},
),
Positioned(
bottom: MediaQuery.paddingOf(context).bottom,
child: CustomWidthButton(
text: 'Create Game',
sizeRelativeToWidth: 0.90,
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return const CreateGroupView();
},
),
);
setState(() {
_gameListFuture = db.gameDao.getAllGames();
});
},
),
),
],
),
);
}
}

View File

@@ -1,23 +1,21 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/match.dart'; import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/tiles/custom_radio_list_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/custom_radio_list_tile.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class MatchResultView extends StatefulWidget { class GameResultView extends StatefulWidget {
final Match match; final Game game;
final VoidCallback? onWinnerChanged; const GameResultView({super.key, required this.game});
const MatchResultView({super.key, required this.match, this.onWinnerChanged});
@override @override
State<MatchResultView> createState() => _MatchResultViewState(); State<GameResultView> createState() => _GameResultViewState();
} }
class _MatchResultViewState extends State<MatchResultView> { class _GameResultViewState extends State<GameResultView> {
late final List<Player> allPlayers; late final List<Player> allPlayers;
late final AppDatabase db; late final AppDatabase db;
Player? _selectedPlayer; Player? _selectedPlayer;
@@ -25,10 +23,10 @@ class _MatchResultViewState extends State<MatchResultView> {
@override @override
void initState() { void initState() {
db = Provider.of<AppDatabase>(context, listen: false); db = Provider.of<AppDatabase>(context, listen: false);
allPlayers = getAllPlayers(widget.match); allPlayers = getAllPlayers(widget.game);
if (widget.match.winner != null) { if (widget.game.winner != null) {
_selectedPlayer = allPlayers.firstWhere( _selectedPlayer = allPlayers.firstWhere(
(p) => p.id == widget.match.winner!.id, (p) => p.id == widget.game.winner!.id,
); );
} }
super.initState(); super.initState();
@@ -39,17 +37,10 @@ class _MatchResultViewState extends State<MatchResultView> {
return Scaffold( return Scaffold(
backgroundColor: CustomTheme.backgroundColor, backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar( appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.close),
onPressed: () {
widget.onWinnerChanged?.call();
Navigator.of(context).pop();
},
),
backgroundColor: CustomTheme.backgroundColor, backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0, scrolledUnderElevation: 0,
title: Text( title: Text(
widget.match.name, widget.game.name,
style: const TextStyle( style: const TextStyle(
fontSize: 20, fontSize: 20,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -80,8 +71,8 @@ class _MatchResultViewState extends State<MatchResultView> {
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( const Text(
AppLocalizations.of(context)!.select_winner, 'Select Winner:',
style: TextStyle( style: TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -133,22 +124,21 @@ class _MatchResultViewState extends State<MatchResultView> {
Future<void> _handleWinnerSaving() async { Future<void> _handleWinnerSaving() async {
if (_selectedPlayer == null) { if (_selectedPlayer == null) {
await db.matchDao.removeWinner(matchId: widget.match.id); await db.gameDao.removeWinner(gameId: widget.game.id);
} else { } else {
await db.matchDao.setWinner( await db.gameDao.setWinner(
matchId: widget.match.id, gameId: widget.game.id,
winnerId: _selectedPlayer!.id, winnerId: _selectedPlayer!.id,
); );
} }
widget.onWinnerChanged?.call();
} }
List<Player> getAllPlayers(Match match) { List<Player> getAllPlayers(Game game) {
if (match.group == null && match.players != null) { if (game.group == null && game.players != null) {
return [...match.players!]; return [...game.players!];
} else if (match.group != null && match.players != null) { } else if (game.group != null && game.players != null) {
return [...match.players!, ...match.group!.members]; return [...game.players!, ...game.group!.members];
} }
return [...match.group!.members]; return [...game.group!.members];
} }
} }

View File

@@ -1,116 +0,0 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/constants.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/views/main_menu/group_view/create_group_view.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/tiles/group_tile.dart';
import 'package:game_tracker/presentation/widgets/top_centered_message.dart';
import 'package:provider/provider.dart';
class GroupsView extends StatefulWidget {
const GroupsView({super.key});
@override
State<GroupsView> createState() => _GroupsViewState();
}
class _GroupsViewState extends State<GroupsView> {
late final AppDatabase db;
late List<Group> loadedGroups;
bool isLoading = true;
List<Group> groups = List.filled(
7,
Group(
name: 'Skeleton Group',
members: List.filled(6, Player(name: 'Skeleton Player')),
),
);
@override
void initState() {
super.initState();
db = Provider.of<AppDatabase>(context, listen: false);
loadGroups();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
body: Stack(
alignment: Alignment.center,
children: [
AppSkeleton(
enabled: isLoading,
child: Visibility(
visible: groups.isNotEmpty,
replacement: Center(
child: TopCenteredMessage(
icon: Icons.info,
title: AppLocalizations.of(context)!.info,
message: AppLocalizations.of(context)!.no_groups_created_yet,
),
),
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: groups.length + 1,
itemBuilder: (BuildContext context, int index) {
if (index == groups.length) {
return SizedBox(
height: MediaQuery.paddingOf(context).bottom - 20,
);
}
return GroupTile(group: groups[index]);
},
),
),
),
Positioned(
bottom: MediaQuery.paddingOf(context).bottom,
child: CustomWidthButton(
text: AppLocalizations.of(context)!.create_group,
sizeRelativeToWidth: 0.90,
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return const CreateGroupView();
},
),
);
setState(() {
loadGroups();
});
},
),
),
],
),
);
}
void loadGroups() {
Future.wait([
db.groupDao.getAllGroups(),
Future.delayed(minimumSkeletonDuration),
]).then((results) {
loadedGroups = results[0] as List<Group>;
setState(() {
groups = loadedGroups
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
});
if (mounted) {
setState(() {
isLoading = false;
});
}
});
}
}

View File

@@ -0,0 +1,119 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/presentation/views/main_menu/create_group_view.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/tiles/group_tile.dart';
import 'package:game_tracker/presentation/widgets/top_centered_message.dart';
import 'package:provider/provider.dart';
class GroupsView extends StatefulWidget {
const GroupsView({super.key});
@override
State<GroupsView> createState() => _GroupsViewState();
}
class _GroupsViewState extends State<GroupsView> {
late Future<List<Group>> _allGroupsFuture;
late final AppDatabase db;
final player = Player(name: 'Skeleton Player');
late final List<Group> skeletonData = List.filled(
7,
Group(
name: 'Skeleton Game',
members: [player, player, player, player, player, player],
),
);
@override
void initState() {
super.initState();
db = Provider.of<AppDatabase>(context, listen: false);
_allGroupsFuture = Future.delayed(
const Duration(milliseconds: 250),
() => db.groupDao.getAllGroups(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
body: Stack(
alignment: Alignment.center,
children: [
FutureBuilder<List<Group>>(
future: _allGroupsFuture,
builder:
(BuildContext context, AsyncSnapshot<List<Group>> snapshot) {
if (snapshot.hasError) {
return const Center(
child: TopCenteredMessage(
icon: Icons.report,
title: 'Error',
message: 'Group data couldn\'t\nbe loaded',
),
);
}
if (snapshot.connectionState == ConnectionState.done &&
(!snapshot.hasData || snapshot.data!.isEmpty)) {
return const Center(
child: TopCenteredMessage(
icon: Icons.info,
title: 'Info',
message: 'No groups created yet',
),
);
}
final bool isLoading =
snapshot.connectionState == ConnectionState.waiting;
final List<Group> groups =
isLoading ? skeletonData : (snapshot.data ?? [])
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
return AppSkeleton(
enabled: isLoading,
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: groups.length + 1,
itemBuilder: (BuildContext context, int index) {
if (index == groups.length) {
return SizedBox(
height: MediaQuery.paddingOf(context).bottom - 20,
);
}
return GroupTile(group: groups[index]);
},
),
);
},
),
Positioned(
bottom: MediaQuery.paddingOf(context).bottom,
child: CustomWidthButton(
text: 'Create Group',
sizeRelativeToWidth: 0.90,
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return const CreateGroupView();
},
),
);
setState(() {
_allGroupsFuture = db.groupDao.getAllGroups();
});
},
),
),
],
),
);
}
}

View File

@@ -1,10 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/constants.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart'; import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart'; import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/buttons/quick_create_button.dart'; import 'package:game_tracker/presentation/widgets/buttons/quick_create_button.dart';
import 'package:game_tracker/presentation/widgets/tiles/game_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/game_tile.dart';
@@ -20,14 +18,15 @@ class HomeView extends StatefulWidget {
} }
class _HomeViewState extends State<HomeView> { class _HomeViewState extends State<HomeView> {
late Future<int> _gameCountFuture;
late Future<int> _groupCountFuture;
late Future<List<Game>> _recentGamesFuture;
bool isLoading = true; bool isLoading = true;
int matchCount = 0;
int groupCount = 0; late final List<Game> skeletonData = List.filled(
List<Match> loadedRecentMatches = [];
List<Match> recentMatches = List.filled(
2, 2,
Match( Game(
name: 'Skeleton Match', name: 'Skeleton Game',
group: Group( group: Group(
name: 'Skeleton Group', name: 'Skeleton Group',
members: [ members: [
@@ -40,34 +39,23 @@ class _HomeViewState extends State<HomeView> {
); );
@override @override
void initState() { initState() {
super.initState(); super.initState();
final db = Provider.of<AppDatabase>(context, listen: false); final db = Provider.of<AppDatabase>(context, listen: false);
Future.wait([ _gameCountFuture = db.gameDao.getGameCount();
db.matchDao.getMatchCount(), _groupCountFuture = db.groupDao.getGroupCount();
db.groupDao.getGroupCount(), _recentGamesFuture = db.gameDao.getAllGames();
db.matchDao.getAllMatches(),
Future.delayed(minimumSkeletonDuration), Future.wait([_gameCountFuture, _groupCountFuture, _recentGamesFuture]).then(
]).then((results) { (_) async {
matchCount = results[0] as int; await Future.delayed(const Duration(milliseconds: 250));
groupCount = results[1] as int; if (mounted) {
loadedRecentMatches = results[2] as List<Match>; setState(() {
recentMatches = isLoading = false;
(loadedRecentMatches });
..sort((a, b) => b.createdAt.compareTo(a.createdAt))) }
.take(2) },
.toList(); );
if (loadedRecentMatches.length < 2) {
recentMatches.add(
Match(name: 'Dummy Match', winner: null, group: null, players: null),
);
}
if (mounted) {
setState(() {
isLoading = false;
});
}
});
} }
@override @override
@@ -75,7 +63,6 @@ class _HomeViewState extends State<HomeView> {
return LayoutBuilder( return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) { builder: (BuildContext context, BoxConstraints constraints) {
return AppSkeleton( return AppSkeleton(
fixLayoutBuilder: true,
enabled: isLoading, enabled: isLoading,
child: SingleChildScrollView( child: SingleChildScrollView(
child: Column( child: Column(
@@ -84,20 +71,38 @@ class _HomeViewState extends State<HomeView> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
QuickInfoTile( FutureBuilder<int>(
width: constraints.maxWidth * 0.45, future: _gameCountFuture,
height: constraints.maxHeight * 0.15, builder: (context, snapshot) {
title: AppLocalizations.of(context)!.matches, final int count = (snapshot.hasData)
icon: Icons.groups_rounded, ? snapshot.data!
value: matchCount, : 0;
return QuickInfoTile(
width: constraints.maxWidth * 0.45,
height: constraints.maxHeight * 0.15,
title: 'Games',
icon: Icons.groups_rounded,
value: count,
);
},
), ),
SizedBox(width: constraints.maxWidth * 0.05), SizedBox(width: constraints.maxWidth * 0.05),
QuickInfoTile( FutureBuilder<int>(
width: constraints.maxWidth * 0.45, future: _groupCountFuture,
height: constraints.maxHeight * 0.15, builder: (context, snapshot) {
title: AppLocalizations.of(context)!.groups, final int count =
icon: Icons.groups_rounded, (snapshot.connectionState == ConnectionState.done &&
value: groupCount, snapshot.hasData)
? snapshot.data!
: 0;
return QuickInfoTile(
width: constraints.maxWidth * 0.45,
height: constraints.maxHeight * 0.15,
title: 'Groups',
icon: Icons.groups_rounded,
value: count,
);
},
), ),
], ],
), ),
@@ -105,79 +110,94 @@ class _HomeViewState extends State<HomeView> {
padding: const EdgeInsets.symmetric(vertical: 16.0), padding: const EdgeInsets.symmetric(vertical: 16.0),
child: InfoTile( child: InfoTile(
width: constraints.maxWidth * 0.95, width: constraints.maxWidth * 0.95,
title: AppLocalizations.of(context)!.recent_matches, title: 'Recent Games',
icon: Icons.timer, icon: Icons.timer,
content: Padding( content: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0), padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: Visibility( child: FutureBuilder(
visible: !isLoading && loadedRecentMatches.isNotEmpty, future: _recentGamesFuture,
replacement: Center( builder:
heightFactor: 12, (
child: Text( BuildContext context,
AppLocalizations.of( AsyncSnapshot<List<Game>> snapshot,
context, ) {
)!.no_recent_matches_available, if (snapshot.hasError) {
), return const Center(
), heightFactor: 4,
child: Column( child: Text(
mainAxisAlignment: MainAxisAlignment.start, 'Error while loading recent games.',
crossAxisAlignment: CrossAxisAlignment.start, ),
children: [ );
MatchTile( }
matchTitle: recentMatches[0].name, final List<Game> games =
game: AppLocalizations.of(context)!.winner_label, (isLoading
ruleset: AppLocalizations.of( ? skeletonData
context, : (snapshot.data ?? [])
)!.ruleset_label, ..sort(
players: _getPlayerText(recentMatches[0]), (a, b) => b.createdAt.compareTo(
winner: recentMatches[0].winner == null a.createdAt,
? AppLocalizations.of( ),
context, ))
)!.match_in_progress .take(2)
: recentMatches[0].winner!.name, .toList();
), if (games.isNotEmpty) {
const Padding( return Column(
padding: EdgeInsets.symmetric(vertical: 8.0), mainAxisAlignment: MainAxisAlignment.start,
child: Divider(), crossAxisAlignment: CrossAxisAlignment.start,
), children: [
if (loadedRecentMatches.length > 1) ...[ GameTile(
MatchTile( gameTitle: games[0].name,
matchTitle: recentMatches[1].name, gameType: 'Winner',
game: AppLocalizations.of( ruleset: 'Ruleset',
context, players: _getPlayerText(games[0]),
)!.winner_label, winner: games[0].winner == null
ruleset: AppLocalizations.of( ? 'Game in progress...'
context, : games[0].winner!.name,
)!.ruleset_label, ),
players: _getPlayerText(recentMatches[1]), const Padding(
winner: recentMatches[1].winner == null padding: EdgeInsets.symmetric(
? AppLocalizations.of( vertical: 8.0,
context, ),
)!.match_in_progress child: Divider(),
: recentMatches[1].winner!.name, ),
), if (games.length > 1) ...[
const SizedBox(height: 8), GameTile(
] else ...[ gameTitle: games[1].name,
Center( gameType: 'Winner',
heightFactor: 5.35, ruleset: 'Ruleset',
child: Text( players: _getPlayerText(games[1]),
AppLocalizations.of( winner: games[1].winner == null
context, ? 'Game in progress...'
)!.no_second_match_available, : games[1].winner!.name,
), ),
), const SizedBox(height: 8),
], ] else ...[
], const Center(
), heightFactor: 4,
child: Text(
'No second game available.',
),
),
],
],
);
} else {
return const Center(
heightFactor: 12,
child: Text('No recent games available.'),
);
}
},
), ),
), ),
), ),
), ),
InfoTile( InfoTile(
width: constraints.maxWidth * 0.95, width: constraints.maxWidth * 0.95,
title: AppLocalizations.of(context)!.quick_create, title: 'Quick Create',
icon: Icons.add_box_rounded, icon: Icons.add_box_rounded,
content: Column( content: Column(
spacing: 8,
children: [ children: [
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
@@ -229,10 +249,10 @@ class _HomeViewState extends State<HomeView> {
); );
} }
String _getPlayerText(Match game) { String _getPlayerText(Game game) {
if (game.group == null) { if (game.group == null) {
final playerCount = game.players?.length ?? 0; final playerCount = game.players?.length ?? 0;
return AppLocalizations.of(context)!.players_count(playerCount); return '$playerCount Players';
} }
if (game.players == null || game.players!.isEmpty) { if (game.players == null || game.players!.isEmpty) {
return game.group!.name; return game.group!.name;

View File

@@ -1,89 +0,0 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/text_input/custom_search_bar.dart';
import 'package:game_tracker/presentation/widgets/tiles/title_description_list_tile.dart';
class ChooseGameView extends StatefulWidget {
final List<(String, String, Ruleset)> games;
final int initialGameIndex;
const ChooseGameView({
super.key,
required this.games,
required this.initialGameIndex,
});
@override
State<ChooseGameView> createState() => _ChooseGameViewState();
}
class _ChooseGameViewState extends State<ChooseGameView> {
late int selectedGameIndex;
final TextEditingController searchBarController = TextEditingController();
@override
void initState() {
selectedGameIndex = widget.initialGameIndex;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.of(context).pop(selectedGameIndex);
},
),
title: Text(
AppLocalizations.of(context)!.choose_game,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: CustomSearchBar(
controller: searchBarController,
hintText: AppLocalizations.of(context)!.game_name,
),
),
const SizedBox(height: 5),
Expanded(
child: ListView.builder(
itemCount: widget.games.length,
itemBuilder: (BuildContext context, int index) {
return TitleDescriptionListTile(
title: widget.games[index].$1,
description: widget.games[index].$2,
badgeText: translateRulesetToString(
widget.games[index].$3,
context,
),
onPressed: () async {
setState(() {
if (selectedGameIndex == index) {
selectedGameIndex = -1;
} else {
selectedGameIndex = index;
}
});
},
);
},
),
),
],
),
);
}
}

View File

@@ -1,138 +0,0 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/text_input/custom_search_bar.dart';
import 'package:game_tracker/presentation/widgets/tiles/group_tile.dart';
import 'package:game_tracker/presentation/widgets/top_centered_message.dart';
class ChooseGroupView extends StatefulWidget {
final List<Group> groups;
final String initialGroupId;
const ChooseGroupView({
super.key,
required this.groups,
required this.initialGroupId,
});
@override
State<ChooseGroupView> createState() => _ChooseGroupViewState();
}
class _ChooseGroupViewState extends State<ChooseGroupView> {
late String selectedGroupId;
final TextEditingController controller = TextEditingController();
late final List<Group> filteredGroups;
@override
void initState() {
selectedGroupId = widget.initialGroupId;
filteredGroups = [...widget.groups];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.of(context).pop(
selectedGroupId == ''
? null
: widget.groups.firstWhere(
(group) => group.id == selectedGroupId,
),
);
},
),
title: Text(
AppLocalizations.of(context)!.choose_group,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: CustomSearchBar(
controller: controller,
hintText: AppLocalizations.of(context)!.group_name,
onChanged: (value) {
setState(() {
filterGroups(value);
});
},
),
),
Expanded(
child: Visibility(
visible: filteredGroups.isNotEmpty,
replacement: Visibility(
visible: widget.groups.isNotEmpty,
replacement: TopCenteredMessage(
icon: Icons.info,
title: AppLocalizations.of(context)!.info,
message: AppLocalizations.of(context)!.no_groups_created_yet,
),
child: TopCenteredMessage(
icon: Icons.info,
title: AppLocalizations.of(context)!.info,
message: AppLocalizations.of(
context,
)!.there_is_no_group_matching_your_search,
),
),
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: filteredGroups.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
if (selectedGroupId != filteredGroups[index].id) {
selectedGroupId = filteredGroups[index].id;
} else {
selectedGroupId = '';
}
});
},
child: GroupTile(
group: filteredGroups[index],
isHighlighted:
selectedGroupId == filteredGroups[index].id,
),
);
},
),
),
),
],
),
);
}
/// Filters the groups based on the search query.
/// TODO: Maybe implement also targetting player names?
void filterGroups(String query) {
setState(() {
if (query.isEmpty) {
filteredGroups.clear();
filteredGroups.addAll(widget.groups);
} else {
filteredGroups.clear();
filteredGroups.addAll(
widget.groups.where(
(group) => group.name.toLowerCase().contains(query.toLowerCase()),
),
);
}
});
}
}

View File

@@ -1,82 +0,0 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/tiles/title_description_list_tile.dart';
class ChooseRulesetView extends StatefulWidget {
final List<(Ruleset, String)> rulesets;
final int initialRulesetIndex;
const ChooseRulesetView({
super.key,
required this.rulesets,
required this.initialRulesetIndex,
});
@override
State<ChooseRulesetView> createState() => _ChooseRulesetViewState();
}
class _ChooseRulesetViewState extends State<ChooseRulesetView> {
late int selectedRulesetIndex;
@override
void initState() {
selectedRulesetIndex = widget.initialRulesetIndex;
super.initState();
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
initialIndex: 0,
child: Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.of(context).pop(
selectedRulesetIndex == -1
? null
: widget.rulesets[selectedRulesetIndex].$1,
);
},
),
title: Text(
AppLocalizations.of(context)!.choose_ruleset,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: widget.rulesets.length,
itemBuilder: (BuildContext context, int index) {
return TitleDescriptionListTile(
onPressed: () async {
setState(() {
if (selectedRulesetIndex == index) {
selectedRulesetIndex = -1;
} else {
selectedRulesetIndex = index;
}
});
},
title: translateRulesetToString(
widget.rulesets[index].$1,
context,
),
description: widget.rulesets[index].$2,
isHighlighted: selectedRulesetIndex == index,
);
},
),
),
);
}
}

View File

@@ -1,266 +0,0 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/create_match/choose_game_view.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/create_match/choose_group_view.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/create_match/choose_ruleset_view.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/match_result_view.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/player_selection.dart';
import 'package:game_tracker/presentation/widgets/text_input/text_input_field.dart';
import 'package:game_tracker/presentation/widgets/tiles/choose_tile.dart';
import 'package:provider/provider.dart';
class CreateMatchView extends StatefulWidget {
final VoidCallback? onWinnerChanged;
const CreateMatchView({super.key, this.onWinnerChanged});
@override
State<CreateMatchView> createState() => _CreateMatchViewState();
}
class _CreateMatchViewState extends State<CreateMatchView> {
/// Reference to the app database
late final AppDatabase db;
/// Controller for the match name input field
final TextEditingController _matchNameController = TextEditingController();
/// List of all groups from the database
List<Group> groupsList = [];
/// List of all players from the database
List<Player> playerList = [];
/// List of players filtered based on the selected group
/// If a group is selected, this list contains all players from [playerList]
/// who are not members of the selected group. If no group is selected,
/// this list is identical to [playerList].
List<Player> filteredPlayerList = [];
/// The currently selected group
Group? selectedGroup;
/// The index of the currently selected group in [groupsList] to mark it in
/// the [ChooseGroupView]
String selectedGroupId = '';
/// The currently selected ruleset
Ruleset? selectedRuleset;
/// The index of the currently selected ruleset in [rulesets] to mark it in
/// the [ChooseRulesetView]
int selectedRulesetIndex = -1;
/// The index of the currently selected game in [games] to mark it in
/// the [ChooseGameView]
int selectedGameIndex = -1;
/// The currently selected players
List<Player>? selectedPlayers;
@override
void initState() {
super.initState();
_matchNameController.addListener(() {
setState(() {});
});
db = Provider.of<AppDatabase>(context, listen: false);
Future.wait([
db.groupDao.getAllGroups(),
db.playerDao.getAllPlayers(),
]).then((result) async {
groupsList = result[0] as List<Group>;
playerList = result[1] as List<Player>;
});
filteredPlayerList = List.from(playerList);
}
List<(Ruleset, String)> _getRulesets(BuildContext context) {
return [
(
Ruleset.singleWinner,
AppLocalizations.of(context)!.ruleset_single_winner_desc,
),
(
Ruleset.singleLoser,
AppLocalizations.of(context)!.ruleset_single_loser_desc,
),
(
Ruleset.mostPoints,
AppLocalizations.of(context)!.ruleset_most_points_desc,
),
(
Ruleset.leastPoints,
AppLocalizations.of(context)!.ruleset_least_points_desc,
),
];
}
// TODO: Replace when games are implemented
List<(String, String, Ruleset)> games = [
('Example Game 1', 'This is a description', Ruleset.leastPoints),
('Example Game 2', '', Ruleset.singleWinner),
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
appBar: AppBar(
backgroundColor: CustomTheme.backgroundColor,
scrolledUnderElevation: 0,
title: Text(
AppLocalizations.of(context)!.create_new_match,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
child: TextInputField(
controller: _matchNameController,
hintText: AppLocalizations.of(context)!.match_name,
),
),
ChooseTile(
title: AppLocalizations.of(context)!.game,
trailingText: selectedGameIndex == -1
? AppLocalizations.of(context)!.none
: games[selectedGameIndex].$1,
onPressed: () async {
selectedGameIndex = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChooseGameView(
games: games,
initialGameIndex: selectedGameIndex,
),
),
);
setState(() {
if (selectedGameIndex != -1) {
selectedRuleset = games[selectedGameIndex].$3;
selectedRulesetIndex = _getRulesets(
context,
).indexWhere((r) => r.$1 == selectedRuleset);
} else {
selectedRuleset = null;
}
});
},
),
ChooseTile(
title: AppLocalizations.of(context)!.ruleset,
trailingText: selectedRuleset == null
? AppLocalizations.of(context)!.none
: translateRulesetToString(selectedRuleset!, context),
onPressed: () async {
selectedRuleset = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChooseRulesetView(
rulesets: _getRulesets(context),
initialRulesetIndex: selectedRulesetIndex,
),
),
);
selectedRulesetIndex = _getRulesets(
context,
).indexWhere((r) => r.$1 == selectedRuleset);
selectedGameIndex = -1;
setState(() {});
},
),
ChooseTile(
title: AppLocalizations.of(context)!.group,
trailingText: selectedGroup == null
? AppLocalizations.of(context)!.none
: selectedGroup!.name,
onPressed: () async {
selectedGroup = await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ChooseGroupView(
groups: groupsList,
initialGroupId: selectedGroupId,
),
),
);
selectedGroupId = selectedGroup?.id ?? '';
if (selectedGroup != null) {
filteredPlayerList = playerList
.where(
(p) => !selectedGroup!.members.any((m) => m.id == p.id),
)
.toList();
} else {
filteredPlayerList = List.from(playerList);
}
setState(() {});
},
),
Expanded(
child: PlayerSelection(
key: ValueKey(selectedGroup?.id ?? 'no_group'),
initialSelectedPlayers: selectedPlayers ?? [],
availablePlayers: filteredPlayerList,
onChanged: (value) {
setState(() {
selectedPlayers = value;
});
},
),
),
CustomWidthButton(
text: AppLocalizations.of(context)!.create_match,
sizeRelativeToWidth: 0.95,
buttonType: ButtonType.primary,
onPressed: _enableCreateGameButton()
? () async {
Match match = Match(
name: _matchNameController.text.trim(),
createdAt: DateTime.now(),
group: selectedGroup,
players: selectedPlayers,
);
await db.matchDao.addMatch(match: match);
if (context.mounted) {
Navigator.pushReplacement(
context,
CupertinoPageRoute(
fullscreenDialog: true,
builder: (context) => MatchResultView(
match: match,
onWinnerChanged: widget.onWinnerChanged,
),
),
);
}
}
: null,
),
],
),
),
);
}
/// Determines whether the "Create Game" button should be enabled based on
/// the current state of the input fields.
bool _enableCreateGameButton() {
return _matchNameController.text.isNotEmpty &&
(selectedGroup != null ||
(selectedPlayers != null && selectedPlayers!.length > 1)) &&
selectedRuleset != null;
}
}

View File

@@ -1,133 +0,0 @@
import 'dart:core' hide Match;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:game_tracker/core/constants.dart';
import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/create_match/create_match_view.dart';
import 'package:game_tracker/presentation/views/main_menu/match_view/match_result_view.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/buttons/custom_width_button.dart';
import 'package:game_tracker/presentation/widgets/tiles/game_history_tile.dart';
import 'package:game_tracker/presentation/widgets/top_centered_message.dart';
import 'package:provider/provider.dart';
class MatchView extends StatefulWidget {
const MatchView({super.key});
@override
State<MatchView> createState() => _MatchViewState();
}
class _MatchViewState extends State<MatchView> {
late final AppDatabase db;
bool isLoading = true;
List<Match> matches = List.filled(
4,
Match(
name: 'Skeleton Gamename',
group: Group(
name: 'Groupname',
members: List.filled(5, Player(name: 'Player')),
),
winner: Player(name: 'Player'),
players: [Player(name: 'Player')],
),
);
@override
void initState() {
super.initState();
db = Provider.of<AppDatabase>(context, listen: false);
loadGames();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: CustomTheme.backgroundColor,
body: Stack(
alignment: Alignment.center,
children: [
AppSkeleton(
enabled: isLoading,
child: Visibility(
visible: matches.isNotEmpty,
replacement: Center(
child: TopCenteredMessage(
icon: Icons.report,
title: AppLocalizations.of(context)!.info,
message: AppLocalizations.of(context)!.no_matches_created_yet,
),
),
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 85),
itemCount: matches.length + 1,
itemBuilder: (BuildContext context, int index) {
if (index == matches.length) {
return SizedBox(
height: MediaQuery.paddingOf(context).bottom - 80,
);
}
return GameHistoryTile(
onTap: () async {
Navigator.push(
context,
CupertinoPageRoute(
fullscreenDialog: true,
builder: (context) => MatchResultView(
match: matches[index],
onWinnerChanged: loadGames,
),
),
);
},
match: matches[index],
);
},
),
),
),
Positioned(
bottom: MediaQuery.paddingOf(context).bottom,
child: CustomWidthButton(
text: AppLocalizations.of(context)!.create_match,
sizeRelativeToWidth: 0.90,
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
CreateMatchView(onWinnerChanged: loadGames),
),
);
},
),
),
],
),
);
}
void loadGames() {
Future.wait([
db.matchDao.getAllMatches(),
Future.delayed(minimumSkeletonDuration),
]).then((results) {
if (mounted) {
setState(() {
final loadedMatches = results[0] as List<Match>;
matches = loadedMatches
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
isLoading = false;
});
}
});
}
}

View File

@@ -1,7 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/core/enums.dart'; import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/tiles/settings_list_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/settings_list_tile.dart';
import 'package:game_tracker/services/data_transfer_service.dart'; import 'package:game_tracker/services/data_transfer_service.dart';
@@ -25,33 +24,30 @@ class _SettingsViewState extends State<SettingsView> {
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Padding( const Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 10), padding: EdgeInsets.fromLTRB(24, 0, 24, 10),
child: Text( child: Text(
textAlign: TextAlign.start, textAlign: TextAlign.start,
AppLocalizations.of(context)!.menu, 'Menu',
style: const TextStyle( style: TextStyle(
fontSize: 28, fontSize: 28,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
), ),
Padding( const Padding(
padding: const EdgeInsets.symmetric( padding: EdgeInsets.symmetric(horizontal: 24, vertical: 10),
horizontal: 24,
vertical: 10,
),
child: Text( child: Text(
textAlign: TextAlign.start, textAlign: TextAlign.start,
AppLocalizations.of(context)!.settings, 'Settings',
style: const TextStyle( style: TextStyle(
fontSize: 22, fontSize: 22,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
), ),
SettingsListTile( SettingsListTile(
title: AppLocalizations.of(context)!.export_data, title: 'Export data',
icon: Icons.upload_outlined, icon: Icons.upload_outlined,
suffixWidget: const Icon(Icons.arrow_forward_ios, size: 16), suffixWidget: const Icon(Icons.arrow_forward_ios, size: 16),
onPressed: () async { onPressed: () async {
@@ -66,7 +62,7 @@ class _SettingsViewState extends State<SettingsView> {
}, },
), ),
SettingsListTile( SettingsListTile(
title: AppLocalizations.of(context)!.import_data, title: 'Import data',
icon: Icons.download_outlined, icon: Icons.download_outlined,
suffixWidget: const Icon(Icons.arrow_forward_ios, size: 16), suffixWidget: const Icon(Icons.arrow_forward_ios, size: 16),
onPressed: () async { onPressed: () async {
@@ -78,27 +74,23 @@ class _SettingsViewState extends State<SettingsView> {
}, },
), ),
SettingsListTile( SettingsListTile(
title: AppLocalizations.of(context)!.delete_all_data, title: 'Delete all data',
icon: Icons.download_outlined, icon: Icons.download_outlined,
suffixWidget: const Icon(Icons.arrow_forward_ios, size: 16), suffixWidget: const Icon(Icons.arrow_forward_ios, size: 16),
onPressed: () { onPressed: () {
showDialog<bool>( showDialog<bool>(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
title: Text( title: const Text('Delete all data?'),
AppLocalizations.of(context)!.delete_all_data, content: const Text('This can\'t be undone'),
),
content: Text(
AppLocalizations.of(context)!.this_cannot_be_undone,
),
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.of(context).pop(false), onPressed: () => Navigator.of(context).pop(false),
child: Text(AppLocalizations.of(context)!.cancel), child: const Text('Abbrechen'),
), ),
TextButton( TextButton(
onPressed: () => Navigator.of(context).pop(true), onPressed: () => Navigator.of(context).pop(true),
child: Text(AppLocalizations.of(context)!.delete), child: const Text('Löschen'),
), ),
], ],
), ),
@@ -107,9 +99,7 @@ class _SettingsViewState extends State<SettingsView> {
DataTransferService.deleteAllData(context); DataTransferService.deleteAllData(context);
showSnackbar( showSnackbar(
context: context, context: context,
message: AppLocalizations.of( message: 'Daten erfolgreich gelöscht',
context,
)!.data_successfully_deleted,
); );
} }
}); });
@@ -132,34 +122,22 @@ class _SettingsViewState extends State<SettingsView> {
}) { }) {
switch (result) { switch (result) {
case ImportResult.success: case ImportResult.success:
showSnackbar( showSnackbar(context: context, message: 'Data successfully imported');
context: context,
message: AppLocalizations.of(context)!.data_successfully_imported,
);
case ImportResult.invalidSchema: case ImportResult.invalidSchema:
showSnackbar( showSnackbar(context: context, message: 'Invalid Schema');
context: context,
message: AppLocalizations.of(context)!.invalid_schema,
);
case ImportResult.fileReadError: case ImportResult.fileReadError:
showSnackbar( showSnackbar(context: context, message: 'Error reading file');
context: context,
message: AppLocalizations.of(context)!.error_reading_file,
);
case ImportResult.canceled: case ImportResult.canceled:
showSnackbar( showSnackbar(context: context, message: 'Import canceled');
context: context,
message: AppLocalizations.of(context)!.import_canceled,
);
case ImportResult.formatException: case ImportResult.formatException:
showSnackbar( showSnackbar(
context: context, context: context,
message: AppLocalizations.of(context)!.format_exception, message: 'Format Exception (see console)',
); );
case ImportResult.unknownException: case ImportResult.unknownException:
showSnackbar( showSnackbar(
context: context, context: context,
message: AppLocalizations.of(context)!.unknown_exception, message: 'Unknown Exception (see console)',
); );
} }
} }
@@ -174,19 +152,13 @@ class _SettingsViewState extends State<SettingsView> {
}) { }) {
switch (result) { switch (result) {
case ExportResult.success: case ExportResult.success:
showSnackbar( showSnackbar(context: context, message: 'Data successfully exported');
context: context,
message: AppLocalizations.of(context)!.data_successfully_exported,
);
case ExportResult.canceled: case ExportResult.canceled:
showSnackbar( showSnackbar(context: context, message: 'Export canceled');
context: context,
message: AppLocalizations.of(context)!.export_canceled,
);
case ExportResult.unknownException: case ExportResult.unknownException:
showSnackbar( showSnackbar(
context: context, context: context,
message: AppLocalizations.of(context)!.unknown_exception, message: 'Unknown Exception (see console)',
); );
} }
} }
@@ -211,10 +183,7 @@ class _SettingsViewState extends State<SettingsView> {
backgroundColor: CustomTheme.onBoxColor, backgroundColor: CustomTheme.onBoxColor,
duration: duration, duration: duration,
action: action != null action: action != null
? SnackBarAction( ? SnackBarAction(label: 'Rückgängig', onPressed: action)
label: AppLocalizations.of(context)!.undo,
onPressed: action,
)
: null, : null,
), ),
); );

View File

@@ -1,9 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/constants.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/match.dart'; import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart'; import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/tiles/statistics_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/statistics_tile.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -16,8 +14,10 @@ class StatisticsView extends StatefulWidget {
} }
class _StatisticsViewState extends State<StatisticsView> { class _StatisticsViewState extends State<StatisticsView> {
late Future<List<Game>> _gamesFuture;
late Future<List<Player>> _playersFuture;
List<(String, int)> winCounts = List.filled(6, ('Skeleton Player', 1)); List<(String, int)> winCounts = List.filled(6, ('Skeleton Player', 1));
List<(String, int)> matchCounts = List.filled(6, ('Skeleton Player', 1)); List<(String, int)> gameCounts = List.filled(6, ('Skeleton Player', 1));
List<(String, double)> winRates = List.filled(6, ('Skeleton Player', 1)); List<(String, double)> winRates = List.filled(6, ('Skeleton Player', 1));
bool isLoading = true; bool isLoading = true;
@@ -25,17 +25,16 @@ class _StatisticsViewState extends State<StatisticsView> {
void initState() { void initState() {
super.initState(); super.initState();
final db = Provider.of<AppDatabase>(context, listen: false); final db = Provider.of<AppDatabase>(context, listen: false);
_gamesFuture = db.gameDao.getAllGames();
_playersFuture = db.playerDao.getAllPlayers();
Future.wait([ Future.wait([_gamesFuture, _playersFuture]).then((results) async {
db.matchDao.getAllMatches(), await Future.delayed(const Duration(milliseconds: 250));
db.playerDao.getAllPlayers(), final games = results[0] as List<Game>;
Future.delayed(minimumSkeletonDuration),
]).then((results) async {
final matches = results[0] as List<Match>;
final players = results[1] as List<Player>; final players = results[1] as List<Player>;
winCounts = _calculateWinsForAllPlayers(matches, players); winCounts = _calculateWinsForAllPlayers(games, players);
matchCounts = _calculateMatchAmountsForAllPlayers(matches, players); gameCounts = _calculateGameAmountsForAllPlayers(games, players);
winRates = computeWinRatePercent(wins: winCounts, matches: matchCounts); winRates = computeWinRatePercent(wins: winCounts, games: gameCounts);
if (mounted) { if (mounted) {
setState(() { setState(() {
isLoading = false; isLoading = false;
@@ -61,7 +60,7 @@ class _StatisticsViewState extends State<StatisticsView> {
SizedBox(height: constraints.maxHeight * 0.01), SizedBox(height: constraints.maxHeight * 0.01),
StatisticsTile( StatisticsTile(
icon: Icons.sports_score, icon: Icons.sports_score,
title: AppLocalizations.of(context)!.wins, title: 'Wins per Player',
width: constraints.maxWidth * 0.95, width: constraints.maxWidth * 0.95,
values: winCounts, values: winCounts,
itemCount: 3, itemCount: 3,
@@ -70,7 +69,7 @@ class _StatisticsViewState extends State<StatisticsView> {
SizedBox(height: constraints.maxHeight * 0.02), SizedBox(height: constraints.maxHeight * 0.02),
StatisticsTile( StatisticsTile(
icon: Icons.percent, icon: Icons.percent,
title: AppLocalizations.of(context)!.winrate, title: 'Winrate per Player',
width: constraints.maxWidth * 0.95, width: constraints.maxWidth * 0.95,
values: winRates, values: winRates,
itemCount: 5, itemCount: 5,
@@ -79,9 +78,9 @@ class _StatisticsViewState extends State<StatisticsView> {
SizedBox(height: constraints.maxHeight * 0.02), SizedBox(height: constraints.maxHeight * 0.02),
StatisticsTile( StatisticsTile(
icon: Icons.casino, icon: Icons.casino,
title: AppLocalizations.of(context)!.amount_of_matches, title: 'Games per Player',
width: constraints.maxWidth * 0.95, width: constraints.maxWidth * 0.95,
values: matchCounts, values: gameCounts,
itemCount: 10, itemCount: 10,
barColor: Colors.green, barColor: Colors.green,
), ),
@@ -98,14 +97,14 @@ class _StatisticsViewState extends State<StatisticsView> {
/// Calculates the number of wins for each player /// Calculates the number of wins for each player
/// and returns a sorted list of tuples (playerName, winCount) /// and returns a sorted list of tuples (playerName, winCount)
List<(String, int)> _calculateWinsForAllPlayers( List<(String, int)> _calculateWinsForAllPlayers(
List<Match> matches, List<Game> games,
List<Player> players, List<Player> players,
) { ) {
List<(String, int)> winCounts = []; List<(String, int)> winCounts = [];
// Getting the winners // Getting the winners
for (var match in matches) { for (var game in games) {
final winner = match.winner; final winner = game.winner;
if (winner != null) { if (winner != null) {
final index = winCounts.indexWhere((entry) => entry.$1 == winner.id); final index = winCounts.indexWhere((entry) => entry.$1 == winner.id);
// -1 means winner not found in winCounts // -1 means winner not found in winCounts
@@ -142,83 +141,83 @@ class _StatisticsViewState extends State<StatisticsView> {
return winCounts; return winCounts;
} }
/// Calculates the number of matches played for each player /// Calculates the number of games played for each player
/// and returns a sorted list of tuples (playerName, matchCount) /// and returns a sorted list of tuples (playerName, gameCount)
List<(String, int)> _calculateMatchAmountsForAllPlayers( List<(String, int)> _calculateGameAmountsForAllPlayers(
List<Match> matches, List<Game> games,
List<Player> players, List<Player> players,
) { ) {
List<(String, int)> matchCounts = []; List<(String, int)> gameCounts = [];
// Counting matches for each player // Counting games for each player
for (var match in matches) { for (var game in games) {
if (match.group != null) { if (game.group != null) {
final members = match.group!.members.map((p) => p.id).toList(); final members = game.group!.members.map((p) => p.id).toList();
for (var playerId in members) { for (var playerId in members) {
final index = matchCounts.indexWhere((entry) => entry.$1 == playerId); final index = gameCounts.indexWhere((entry) => entry.$1 == playerId);
// -1 means player not found in matchCounts // -1 means player not found in gameCounts
if (index != -1) { if (index != -1) {
final current = matchCounts[index].$2; final current = gameCounts[index].$2;
matchCounts[index] = (playerId, current + 1); gameCounts[index] = (playerId, current + 1);
} else { } else {
matchCounts.add((playerId, 1)); gameCounts.add((playerId, 1));
} }
} }
} }
if (match.players != null) { if (game.players != null) {
final members = match.players!.map((p) => p.id).toList(); final members = game.players!.map((p) => p.id).toList();
for (var playerId in members) { for (var playerId in members) {
final index = matchCounts.indexWhere((entry) => entry.$1 == playerId); final index = gameCounts.indexWhere((entry) => entry.$1 == playerId);
// -1 means player not found in matchCounts // -1 means player not found in gameCounts
if (index != -1) { if (index != -1) {
final current = matchCounts[index].$2; final current = gameCounts[index].$2;
matchCounts[index] = (playerId, current + 1); gameCounts[index] = (playerId, current + 1);
} else { } else {
matchCounts.add((playerId, 1)); gameCounts.add((playerId, 1));
} }
} }
} }
} }
// Adding all players with zero matches // Adding all players with zero games
for (var player in players) { for (var player in players) {
final index = matchCounts.indexWhere((entry) => entry.$1 == player.id); final index = gameCounts.indexWhere((entry) => entry.$1 == player.id);
// -1 means player not found in matchCounts // -1 means player not found in gameCounts
if (index == -1) { if (index == -1) {
matchCounts.add((player.id, 0)); gameCounts.add((player.id, 0));
} }
} }
// Replace player IDs with names // Replace player IDs with names
for (int i = 0; i < matchCounts.length; i++) { for (int i = 0; i < gameCounts.length; i++) {
final playerId = matchCounts[i].$1; final playerId = gameCounts[i].$1;
final player = players.firstWhere( final player = players.firstWhere(
(p) => p.id == playerId, (p) => p.id == playerId,
orElse: () => Player(id: playerId, name: 'N.a.'), orElse: () => Player(id: playerId, name: 'N.a.'),
); );
matchCounts[i] = (player.name, matchCounts[i].$2); gameCounts[i] = (player.name, gameCounts[i].$2);
} }
matchCounts.sort((a, b) => b.$2.compareTo(a.$2)); gameCounts.sort((a, b) => b.$2.compareTo(a.$2));
return matchCounts; return gameCounts;
} }
// dart // dart
List<(String, double)> computeWinRatePercent({ List<(String, double)> computeWinRatePercent({
required List<(String, int)> wins, required List<(String, int)> wins,
required List<(String, int)> matches, required List<(String, int)> games,
}) { }) {
final Map<String, int> winsMap = {for (var e in wins) e.$1: e.$2}; final Map<String, int> winsMap = {for (var e in wins) e.$1: e.$2};
final Map<String, int> matchesMap = {for (var e in matches) e.$1: e.$2}; final Map<String, int> gamesMap = {for (var e in games) e.$1: e.$2};
// Get all unique player names // Get all unique player names
final names = {...winsMap.keys, ...matchesMap.keys}; final names = {...winsMap.keys, ...gamesMap.keys};
// Calculate win rates // Calculate win rates
final result = names.map((name) { final result = names.map((name) {
final int w = winsMap[name] ?? 0; final int w = winsMap[name] ?? 0;
final int g = matchesMap[name] ?? 0; final int g = gamesMap[name] ?? 0;
// Calculate percentage and round to 2 decimal places // Calculate percentage and round to 2 decimal places
// Avoid division by zero // Avoid division by zero
final double percent = (g > 0) final double percent = (g > 0)

View File

@@ -1,9 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/constants.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/app_skeleton.dart'; import 'package:game_tracker/presentation/widgets/app_skeleton.dart';
import 'package:game_tracker/presentation/widgets/text_input/custom_search_bar.dart'; import 'package:game_tracker/presentation/widgets/text_input/custom_search_bar.dart';
import 'package:game_tracker/presentation/widgets/tiles/text_icon_list_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/text_icon_list_tile.dart';
@@ -13,14 +11,12 @@ import 'package:provider/provider.dart';
class PlayerSelection extends StatefulWidget { class PlayerSelection extends StatefulWidget {
final Function(List<Player> value) onChanged; final Function(List<Player> value) onChanged;
final List<Player> availablePlayers; final List<Player> initialPlayers;
final List<Player>? initialSelectedPlayers;
const PlayerSelection({ const PlayerSelection({
super.key, super.key,
required this.onChanged, required this.onChanged,
this.availablePlayers = const [], this.initialPlayers = const [],
this.initialSelectedPlayers,
}); });
@override @override
@@ -31,7 +27,6 @@ class _PlayerSelectionState extends State<PlayerSelection> {
List<Player> selectedPlayers = []; List<Player> selectedPlayers = [];
List<Player> suggestedPlayers = []; List<Player> suggestedPlayers = [];
List<Player> allPlayers = []; List<Player> allPlayers = [];
bool isLoading = true;
late final TextEditingController _searchBarController = late final TextEditingController _searchBarController =
TextEditingController(); TextEditingController();
late final AppDatabase db; late final AppDatabase db;
@@ -45,44 +40,27 @@ class _PlayerSelectionState extends State<PlayerSelection> {
void initState() { void initState() {
super.initState(); super.initState();
db = Provider.of<AppDatabase>(context, listen: false); db = Provider.of<AppDatabase>(context, listen: false);
suggestedPlayers = skeletonData;
loadPlayerList(); loadPlayerList();
} }
void loadPlayerList() { void loadPlayerList() {
_allPlayersFuture = Future.wait([ _allPlayersFuture = Future.delayed(
db.playerDao.getAllPlayers(), const Duration(milliseconds: 250),
Future.delayed(minimumSkeletonDuration), () => db.playerDao.getAllPlayers(),
]).then((results) => results[0] as List<Player>); );
if (mounted) { suggestedPlayers = skeletonData;
_allPlayersFuture.then((loadedPlayers) { _allPlayersFuture.then((loadedPlayers) {
setState(() { setState(() {
// If a list of available players is provided, use that list. if (widget.initialPlayers.isNotEmpty) {
if (widget.availablePlayers.isNotEmpty) { allPlayers = [...widget.initialPlayers];
widget.availablePlayers.sort((a, b) => a.name.compareTo(b.name)); suggestedPlayers = [...widget.initialPlayers];
allPlayers = [...widget.availablePlayers]; } else {
suggestedPlayers = [...allPlayers]; loadedPlayers.sort((a, b) => a.name.compareTo(b.name));
allPlayers = [...loadedPlayers];
if (widget.initialSelectedPlayers != null) { suggestedPlayers = [...loadedPlayers];
// Ensures that only players available for selection are pre-selected. }
selectedPlayers = widget.initialSelectedPlayers!
.where(
(p) => widget.availablePlayers.any(
(available) => available.id == p.id,
),
)
.toList();
}
} else {
// Otherwise, use the loaded players from the database.
loadedPlayers.sort((a, b) => a.name.compareTo(b.name));
allPlayers = [...loadedPlayers];
suggestedPlayers = [...loadedPlayers];
}
isLoading = false;
});
}); });
} });
} }
@override @override
@@ -130,99 +108,113 @@ class _PlayerSelectionState extends State<PlayerSelection> {
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
Text( Text(
AppLocalizations.of( 'Selected players: (${selectedPlayers.length})',
context,
)!.selected_players(selectedPlayers.length),
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
SizedBox( Wrap(
height: 50, alignment: WrapAlignment.start,
child: selectedPlayers.isEmpty crossAxisAlignment: WrapCrossAlignment.start,
? Center( spacing: 8.0,
child: Text( runSpacing: 8.0,
AppLocalizations.of(context)!.no_players_selected, children: <Widget>[
), // Generates a TextIconTile for each selected player.
) for (var player in selectedPlayers)
: SingleChildScrollView( TextIconTile(
scrollDirection: Axis.horizontal, text: player.name,
child: Row( onIconTap: () {
children: [ setState(() {
for (var player in selectedPlayers) // Removes the player from the selection and notifies the parent.
Padding( final currentSearch = _searchBarController.text
padding: const EdgeInsets.only(right: 8.0), .toLowerCase();
child: TextIconTile( selectedPlayers.remove(player);
text: player.name, widget.onChanged([...selectedPlayers]);
onIconTap: () { // If the player matches the current search query (or search is empty),
setState(() { // they are added back to the suggestions and the list is re-sorted.
// Removes the player from the selection and notifies the parent. if (currentSearch.isEmpty ||
final currentSearch = _searchBarController player.name.toLowerCase().contains(currentSearch)) {
.text suggestedPlayers.add(player);
.toLowerCase(); }
selectedPlayers.remove(player); });
widget.onChanged([...selectedPlayers]); },
// If the player matches the current search query (or search is empty), ),
// they are added back to the suggestions and the list is re-sorted. ],
if (currentSearch.isEmpty ||
player.name.toLowerCase().contains(
currentSearch,
)) {
suggestedPlayers.add(player);
}
});
},
),
),
],
),
),
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
Text( const Text(
AppLocalizations.of(context)!.all_players, 'All players:',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
/* FutureBuilder(
future: _allPlayersFuture,
*/ builder:
Expanded( (BuildContext context, AsyncSnapshot<List<Player>> snapshot) {
child: AppSkeleton( if (snapshot.hasError) {
enabled: isLoading, return const Center(
child: Visibility( child: TopCenteredMessage(
visible: suggestedPlayers.isNotEmpty, icon: Icons.report,
replacement: TopCenteredMessage( title: 'Error',
icon: Icons.info, message: 'Player data couldn\'t\nbe loaded.',
title: AppLocalizations.of(context)!.info, ),
message: allPlayers.isEmpty
? AppLocalizations.of(context)!.no_players_created_yet
: (selectedPlayers.length == allPlayers.length)
? AppLocalizations.of(context)!.all_players_selected
: AppLocalizations.of(
context,
)!.no_players_found_with_that_name,
),
child: ListView.builder(
itemCount: suggestedPlayers.length,
itemBuilder: (BuildContext context, int index) {
return TextIconListTile(
text: suggestedPlayers[index].name,
onPressed: () {
setState(() {
if (!selectedPlayers.contains(
suggestedPlayers[index],
)) {
selectedPlayers.add(suggestedPlayers[index]);
widget.onChanged([...selectedPlayers]);
suggestedPlayers.remove(suggestedPlayers[index]);
}
});
},
); );
}, }
), bool doneLoading =
), snapshot.connectionState == ConnectionState.done;
), bool snapshotDataEmpty =
!snapshot.hasData || snapshot.data!.isEmpty;
if (doneLoading &&
(snapshotDataEmpty && allPlayers.isEmpty)) {
return const Center(
child: TopCenteredMessage(
icon: Icons.info,
title: 'Info',
message: 'No players created yet.',
),
);
}
final bool isLoading =
snapshot.connectionState == ConnectionState.waiting;
return Expanded(
child: AppSkeleton(
enabled: isLoading,
child: Visibility(
visible:
(suggestedPlayers.isEmpty && allPlayers.isNotEmpty),
replacement: ListView.builder(
itemCount: suggestedPlayers.length,
itemBuilder: (BuildContext context, int index) {
return TextIconListTile(
text: suggestedPlayers[index].name,
onPressed: () {
setState(() {
if (!selectedPlayers.contains(
suggestedPlayers[index],
)) {
selectedPlayers.add(
suggestedPlayers[index],
);
widget.onChanged([...selectedPlayers]);
suggestedPlayers.remove(
suggestedPlayers[index],
);
}
});
},
);
},
),
child: TopCenteredMessage(
icon: Icons.info,
title: 'Info',
message: (selectedPlayers.length == allPlayers.length)
? 'No more players to add.'
: 'No players found with that name.',
),
),
),
);
},
), ),
], ],
), ),
@@ -252,9 +244,7 @@ class _PlayerSelectionState extends State<PlayerSelection> {
backgroundColor: CustomTheme.boxColor, backgroundColor: CustomTheme.boxColor,
content: Center( content: Center(
child: Text( child: Text(
AppLocalizations.of( 'Successfully added player $playerName.',
context,
)!.successfully_added_player(playerName),
style: const TextStyle(color: Colors.white), style: const TextStyle(color: Colors.white),
), ),
), ),
@@ -266,7 +256,7 @@ class _PlayerSelectionState extends State<PlayerSelection> {
backgroundColor: CustomTheme.boxColor, backgroundColor: CustomTheme.boxColor,
content: Center( content: Center(
child: Text( child: Text(
AppLocalizations.of(context)!.could_not_add_player(playerName), 'Could not add player $playerName.',
style: const TextStyle(color: Colors.white), style: const TextStyle(color: Colors.white),
), ),
), ),

View File

@@ -30,7 +30,7 @@ class CustomSearchBar extends StatelessWidget {
constraints: constraints:
constraints ?? const BoxConstraints(maxHeight: 45, minHeight: 45), constraints ?? const BoxConstraints(maxHeight: 45, minHeight: 45),
hintText: hintText, hintText: hintText,
onChanged: onChanged, onChanged: trailingButtonEnabled ? onChanged : null,
hintStyle: WidgetStateProperty.all(const TextStyle(fontSize: 16)), hintStyle: WidgetStateProperty.all(const TextStyle(fontSize: 16)),
leading: const Icon(Icons.search), leading: const Icon(Icons.search),
trailing: [ trailing: [

View File

@@ -1,15 +1,14 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:game_tracker/data/dto/match.dart'; import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/tiles/text_icon_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/text_icon_tile.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
class GameHistoryTile extends StatefulWidget { class GameHistoryTile extends StatefulWidget {
final Match match; final Game game;
final VoidCallback onTap; final VoidCallback onTap;
const GameHistoryTile({super.key, required this.match, required this.onTap}); const GameHistoryTile({super.key, required this.game, required this.onTap});
@override @override
State<GameHistoryTile> createState() => _GameHistoryTileState(); State<GameHistoryTile> createState() => _GameHistoryTileState();
@@ -18,8 +17,8 @@ class GameHistoryTile extends StatefulWidget {
class _GameHistoryTileState extends State<GameHistoryTile> { class _GameHistoryTileState extends State<GameHistoryTile> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final group = widget.match.group; final group = widget.game.group;
final winner = widget.match.winner; final winner = widget.game.winner;
final allPlayers = _getAllPlayers(); final allPlayers = _getAllPlayers();
return GestureDetector( return GestureDetector(
@@ -40,7 +39,7 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
children: [ children: [
Expanded( Expanded(
child: Text( child: Text(
widget.match.name, widget.game.name,
style: const TextStyle( style: const TextStyle(
fontSize: 18, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@@ -49,7 +48,7 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
), ),
), ),
Text( Text(
_formatDate(widget.match.createdAt), _formatDate(widget.game.createdAt),
style: const TextStyle(fontSize: 12, color: Colors.grey), style: const TextStyle(fontSize: 12, color: Colors.grey),
), ),
], ],
@@ -98,7 +97,7 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
const SizedBox(width: 8), const SizedBox(width: 8),
Expanded( Expanded(
child: Text( child: Text(
AppLocalizations.of(context)!.winner(winner.name), 'Winner: ${winner.name}',
style: const TextStyle( style: const TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@@ -114,8 +113,8 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
], ],
if (allPlayers.isNotEmpty) ...[ if (allPlayers.isNotEmpty) ...[
Text( const Text(
AppLocalizations.of(context)!.players, 'Players',
style: TextStyle( style: TextStyle(
fontSize: 13, fontSize: 13,
color: Colors.grey, color: Colors.grey,
@@ -142,15 +141,11 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
final difference = now.difference(dateTime); final difference = now.difference(dateTime);
if (difference.inDays == 0) { if (difference.inDays == 0) {
return AppLocalizations.of( return 'Today at ${DateFormat('HH:mm').format(dateTime)}';
context,
)!.today_at(DateFormat('HH:mm').format(dateTime));
} else if (difference.inDays == 1) { } else if (difference.inDays == 1) {
return AppLocalizations.of( return 'Yesterday at ${DateFormat('HH:mm').format(dateTime)}';
context,
)!.yesterday_at(DateFormat('HH:mm').format(dateTime));
} else if (difference.inDays < 7) { } else if (difference.inDays < 7) {
return AppLocalizations.of(context)!.days_ago(difference.inDays); return '${difference.inDays} days ago';
} else { } else {
return DateFormat('MMM d, yyyy').format(dateTime); return DateFormat('MMM d, yyyy').format(dateTime);
} }
@@ -161,8 +156,8 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
final playerIds = <String>{}; final playerIds = <String>{};
// Add players from game.players // Add players from game.players
if (widget.match.players != null) { if (widget.game.players != null) {
for (var player in widget.match.players!) { for (var player in widget.game.players!) {
if (!playerIds.contains(player.id)) { if (!playerIds.contains(player.id)) {
allPlayers.add(player); allPlayers.add(player);
playerIds.add(player.id); playerIds.add(player.id);
@@ -171,8 +166,8 @@ class _GameHistoryTileState extends State<GameHistoryTile> {
} }
// Add players from game.group.players // Add players from game.group.players
if (widget.match.group?.members != null) { if (widget.game.group?.members != null) {
for (var player in widget.match.group!.members) { for (var player in widget.game.group!.members) {
if (!playerIds.contains(player.id)) { if (!playerIds.contains(player.id)) {
allPlayers.add(player); allPlayers.add(player);
playerIds.add(player.id); playerIds.add(player.id);

View File

@@ -2,27 +2,27 @@ import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart'; import 'package:game_tracker/core/custom_theme.dart';
import 'package:skeletonizer/skeletonizer.dart'; import 'package:skeletonizer/skeletonizer.dart';
class MatchTile extends StatefulWidget { class GameTile extends StatefulWidget {
final String matchTitle; final String gameTitle;
final String game; final String gameType;
final String ruleset; final String ruleset;
final String players; final String players;
final String winner; final String winner;
const MatchTile({ const GameTile({
super.key, super.key,
required this.matchTitle, required this.gameTitle,
required this.game, required this.gameType,
required this.ruleset, required this.ruleset,
required this.players, required this.players,
required this.winner, required this.winner,
}); });
@override @override
State<MatchTile> createState() => _MatchTileState(); State<GameTile> createState() => _GameTileState();
} }
class _MatchTileState extends State<MatchTile> { class _GameTileState extends State<GameTile> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Column( return Column(
@@ -31,12 +31,12 @@ class _MatchTileState extends State<MatchTile> {
Row( Row(
children: [ children: [
Text( Text(
widget.matchTitle, widget.gameTitle,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
), ),
const SizedBox(width: 5), const SizedBox(width: 5),
Text( Text(
widget.game, widget.gameType,
style: const TextStyle(fontSize: 14, color: Colors.grey), style: const TextStyle(fontSize: 14, color: Colors.grey),
), ),
], ],

View File

@@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
class RulesetListTile extends StatelessWidget {
final String title;
final String description;
final VoidCallback? onPressed;
final bool isHighlighted;
const RulesetListTile({
super.key,
required this.title,
required this.description,
this.onPressed,
this.isHighlighted = false,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: AnimatedContainer(
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
decoration: isHighlighted
? CustomTheme.highlightedBoxDecoration
: CustomTheme.standardBoxDecoration,
duration: const Duration(milliseconds: 200),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Text(
title,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
],
),
const SizedBox(height: 5),
Text(description, style: const TextStyle(fontSize: 14)),
const SizedBox(height: 2.5),
],
),
),
);
}
}

View File

@@ -1,7 +1,6 @@
import 'dart:math'; import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:game_tracker/l10n/generated/app_localizations.dart';
import 'package:game_tracker/presentation/widgets/tiles/info_tile.dart'; import 'package:game_tracker/presentation/widgets/tiles/info_tile.dart';
class StatisticsTile extends StatelessWidget { class StatisticsTile extends StatelessWidget {
@@ -34,18 +33,18 @@ class StatisticsTile extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 20.0), padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Visibility( child: Visibility(
visible: values.isNotEmpty, visible: values.isNotEmpty,
replacement: Center( replacement: const Center(
heightFactor: 4, heightFactor: 4,
child: Text(AppLocalizations.of(context)!.no_data_available), child: Text('No data available.'),
), ),
child: Column( child: Column(
children: List.generate(min(values.length, itemCount), (index) { children: List.generate(min(values.length, itemCount), (index) {
/// The maximum wins among all players /// The maximum wins among all players
final maxMatches = values.isNotEmpty ? values[0].$2 : 0; final maxGames = values.isNotEmpty ? values[0].$2 : 0;
/// Fraction of wins /// Fraction of wins
final double fraction = (maxMatches > 0) final double fraction = (maxGames > 0)
? (values[index].$2 / maxMatches) ? (values[index].$2 / maxGames)
: 0.0; : 0.0;
/// Calculated width for current the bar /// Calculated width for current the bar

View File

@@ -1,92 +0,0 @@
import 'package:flutter/material.dart';
import 'package:game_tracker/core/custom_theme.dart';
class TitleDescriptionListTile extends StatelessWidget {
final String title;
final String description;
final VoidCallback? onPressed;
final bool isHighlighted;
final String? badgeText;
final Color? badgeColor;
const TitleDescriptionListTile({
super.key,
required this.title,
required this.description,
this.onPressed,
this.isHighlighted = false,
this.badgeText,
this.badgeColor,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: AnimatedContainer(
margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
decoration: isHighlighted
? CustomTheme.highlightedBoxDecoration
: CustomTheme.standardBoxDecoration,
duration: const Duration(milliseconds: 200),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 230,
child: Text(
title,
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: false,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
if (badgeText != null) ...[
const Spacer(),
Container(
constraints: const BoxConstraints(maxWidth: 100),
margin: const EdgeInsets.only(top: 4),
padding: const EdgeInsets.symmetric(
vertical: 2,
horizontal: 6,
),
decoration: BoxDecoration(
color: badgeColor ?? CustomTheme.primaryColor,
borderRadius: BorderRadius.circular(4),
),
child: Text(
badgeText!,
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: false,
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
],
],
),
if (description.isNotEmpty) ...[
const SizedBox(height: 5),
Text(description, style: const TextStyle(fontSize: 14)),
const SizedBox(height: 2.5),
],
],
),
),
);
}
}

View File

@@ -6,8 +6,8 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:game_tracker/core/enums.dart'; import 'package:game_tracker/core/enums.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart'; import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
import 'package:json_schema/json_schema.dart'; import 'package:json_schema/json_schema.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
@@ -16,7 +16,7 @@ class DataTransferService {
/// Deletes all data from the database. /// Deletes all data from the database.
static Future<void> deleteAllData(BuildContext context) async { static Future<void> deleteAllData(BuildContext context) async {
final db = Provider.of<AppDatabase>(context, listen: false); final db = Provider.of<AppDatabase>(context, listen: false);
await db.matchDao.deleteAllMatches(); await db.gameDao.deleteAllGames();
await db.groupDao.deleteAllGroups(); await db.groupDao.deleteAllGroups();
await db.playerDao.deleteAllPlayers(); await db.playerDao.deleteAllPlayers();
} }
@@ -25,13 +25,13 @@ class DataTransferService {
/// Returns the JSON string representation of the data. /// Returns the JSON string representation of the data.
static Future<String> getAppDataAsJson(BuildContext context) async { static Future<String> getAppDataAsJson(BuildContext context) async {
final db = Provider.of<AppDatabase>(context, listen: false); final db = Provider.of<AppDatabase>(context, listen: false);
final matches = await db.matchDao.getAllMatches(); final games = await db.gameDao.getAllGames();
final groups = await db.groupDao.getAllGroups(); final groups = await db.groupDao.getAllGroups();
final players = await db.playerDao.getAllPlayers(); final players = await db.playerDao.getAllPlayers();
// Construct a JSON representation of the data // Construct a JSON representation of the data
final Map<String, dynamic> jsonMap = { final Map<String, dynamic> jsonMap = {
'matches': matches.map((match) => match.toJson()).toList(), 'games': games.map((game) => game.toJson()).toList(),
'groups': groups.map((group) => group.toJson()).toList(), 'groups': groups.map((group) => group.toJson()).toList(),
'players': players.map((player) => player.toJson()).toList(), 'players': players.map((player) => player.toJson()).toList(),
}; };
@@ -89,15 +89,14 @@ class DataTransferService {
final Map<String, dynamic> jsonData = final Map<String, dynamic> jsonData =
json.decode(jsonString) as Map<String, dynamic>; json.decode(jsonString) as Map<String, dynamic>;
final List<dynamic>? matchesJson = final List<dynamic>? gamesJson = jsonData['games'] as List<dynamic>?;
jsonData['matches'] as List<dynamic>?;
final List<dynamic>? groupsJson = jsonData['groups'] as List<dynamic>?; final List<dynamic>? groupsJson = jsonData['groups'] as List<dynamic>?;
final List<dynamic>? playersJson = final List<dynamic>? playersJson =
jsonData['players'] as List<dynamic>?; jsonData['players'] as List<dynamic>?;
final List<Match> importedMatches = final List<Game> importedGames =
matchesJson gamesJson
?.map((g) => Match.fromJson(g as Map<String, dynamic>)) ?.map((g) => Game.fromJson(g as Map<String, dynamic>))
.toList() ?? .toList() ??
[]; [];
final List<Group> importedGroups = final List<Group> importedGroups =
@@ -113,7 +112,7 @@ class DataTransferService {
await db.playerDao.addPlayersAsList(players: importedPlayers); await db.playerDao.addPlayersAsList(players: importedPlayers);
await db.groupDao.addGroupsAsList(groups: importedGroups); await db.groupDao.addGroupsAsList(groups: importedGroups);
await db.matchDao.addMatchAsList(matches: importedMatches); await db.gameDao.addGamesAsList(games: importedGames);
} else { } else {
return ImportResult.invalidSchema; return ImportResult.invalidSchema;
} }

View File

@@ -24,10 +24,7 @@ dependencies:
json_schema: ^5.2.2 json_schema: ^5.2.2
file_saver: ^0.3.1 file_saver: ^0.3.1
clock: ^1.1.2 clock: ^1.1.2
intl: any intl: ^0.18.0
flutter_localizations:
sdk: flutter
auto_localize: ^0.0.5
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
@@ -38,6 +35,5 @@ dev_dependencies:
flutter: flutter:
uses-material-design: true uses-material-design: true
generate: true
assets: assets:
- assets/schema.json - assets/schema.json

View File

@@ -3,8 +3,8 @@ import 'package:drift/drift.dart';
import 'package:drift/native.dart'; import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart'; import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
void main() { void main() {
@@ -16,14 +16,14 @@ void main() {
late Player testPlayer5; late Player testPlayer5;
late Group testGroup1; late Group testGroup1;
late Group testGroup2; late Group testGroup2;
late Match testMatch1; late Game testGame1;
late Match testMatch2; late Game testGame2;
late Match testMatchOnlyPlayers; late Game testGameOnlyPlayers;
late Match testMatchOnlyGroup; late Game testGameOnlyGroup;
final fixedDate = DateTime(2025, 19, 11, 00, 11, 23); final fixedDate = DateTime(2025, 19, 11, 00, 11, 23);
final fakeClock = Clock(() => fixedDate); final fakeClock = Clock(() => fixedDate);
setUp(() async { setUp(() {
database = AppDatabase( database = AppDatabase(
DatabaseConnection( DatabaseConnection(
NativeDatabase.memory(), NativeDatabase.memory(),
@@ -46,61 +46,46 @@ void main() {
name: 'Test Group 2', name: 'Test Group 2',
members: [testPlayer4, testPlayer5], members: [testPlayer4, testPlayer5],
); );
testMatch1 = Match( testGame1 = Game(
name: 'First Test Match', name: 'First Test Game',
group: testGroup1, group: testGroup1,
players: [testPlayer4, testPlayer5], players: [testPlayer4, testPlayer5],
winner: testPlayer4, winner: testPlayer4,
); );
testMatch2 = Match( testGame2 = Game(
name: 'Second Test Match', name: 'Second Test Game',
group: testGroup2, group: testGroup2,
players: [testPlayer1, testPlayer2, testPlayer3], players: [testPlayer1, testPlayer2, testPlayer3],
winner: testPlayer2, winner: testPlayer2,
); );
testMatchOnlyPlayers = Match( testGameOnlyPlayers = Game(
name: 'Test Match with Players', name: 'Test Game with Players',
players: [testPlayer1, testPlayer2, testPlayer3], players: [testPlayer1, testPlayer2, testPlayer3],
winner: testPlayer3, winner: testPlayer3,
); );
testMatchOnlyGroup = Match( testGameOnlyGroup = Game(name: 'Test Game with Group', group: testGroup2);
name: 'Test Match with Group',
group: testGroup2,
);
}); });
await database.playerDao.addPlayersAsList(
players: [
testPlayer1,
testPlayer2,
testPlayer3,
testPlayer4,
testPlayer5,
],
);
await database.groupDao.addGroupsAsList(groups: [testGroup1, testGroup2]);
}); });
tearDown(() async { tearDown(() async {
await database.close(); await database.close();
}); });
group('Match Tests', () { group('Game Tests', () {
test('Adding and fetching single match works correctly', () async { test('Adding and fetching single game works correctly', () async {
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
final result = await database.matchDao.getMatchById( final result = await database.gameDao.getGameById(gameId: testGame1.id);
matchId: testMatch1.id,
);
expect(result.id, testMatch1.id); expect(result.id, testGame1.id);
expect(result.name, testMatch1.name); expect(result.name, testGame1.name);
expect(result.createdAt, testMatch1.createdAt); expect(result.createdAt, testGame1.createdAt);
if (result.winner != null && testMatch1.winner != null) { if (result.winner != null && testGame1.winner != null) {
expect(result.winner!.id, testMatch1.winner!.id); expect(result.winner!.id, testGame1.winner!.id);
expect(result.winner!.name, testMatch1.winner!.name); expect(result.winner!.name, testGame1.winner!.name);
expect(result.winner!.createdAt, testMatch1.winner!.createdAt); expect(result.winner!.createdAt, testGame1.winner!.createdAt);
} else { } else {
expect(result.winner, testMatch1.winner); expect(result.winner, testGame1.winner);
} }
if (result.group != null) { if (result.group != null) {
@@ -114,203 +99,188 @@ void main() {
fail('Group is null'); fail('Group is null');
} }
if (result.players != null) { if (result.players != null) {
expect(result.players!.length, testMatch1.players!.length); expect(result.players!.length, testGame1.players!.length);
for (int i = 0; i < testMatch1.players!.length; i++) { for (int i = 0; i < testGame1.players!.length; i++) {
expect(result.players![i].id, testMatch1.players![i].id); expect(result.players![i].id, testGame1.players![i].id);
expect(result.players![i].name, testMatch1.players![i].name); expect(result.players![i].name, testGame1.players![i].name);
expect( expect(result.players![i].createdAt, testGame1.players![i].createdAt);
result.players![i].createdAt,
testMatch1.players![i].createdAt,
);
} }
} else { } else {
fail('Players is null'); fail('Players is null');
} }
}); });
test('Adding and fetching multiple matches works correctly', () async { test('Adding and fetching multiple games works correctly', () async {
await database.matchDao.addMatchAsList( await database.gameDao.addGamesAsList(
matches: [ games: [testGame1, testGame2, testGameOnlyGroup, testGameOnlyPlayers],
testMatch1,
testMatch2,
testMatchOnlyGroup,
testMatchOnlyPlayers,
],
); );
final allMatches = await database.matchDao.getAllMatches(); final allGames = await database.gameDao.getAllGames();
expect(allMatches.length, 4); expect(allGames.length, 4);
final testMatches = { final testGames = {
testMatch1.id: testMatch1, testGame1.id: testGame1,
testMatch2.id: testMatch2, testGame2.id: testGame2,
testMatchOnlyGroup.id: testMatchOnlyGroup, testGameOnlyGroup.id: testGameOnlyGroup,
testMatchOnlyPlayers.id: testMatchOnlyPlayers, testGameOnlyPlayers.id: testGameOnlyPlayers,
}; };
for (final match in allMatches) { for (final game in allGames) {
final testMatch = testMatches[match.id]!; final testGame = testGames[game.id]!;
// Match-Checks // Game-Checks
expect(match.id, testMatch.id); expect(game.id, testGame.id);
expect(match.name, testMatch.name); expect(game.name, testGame.name);
expect(match.createdAt, testMatch.createdAt); expect(game.createdAt, testGame.createdAt);
if (match.winner != null && testMatch.winner != null) { if (game.winner != null && testGame.winner != null) {
expect(match.winner!.id, testMatch.winner!.id); expect(game.winner!.id, testGame.winner!.id);
expect(match.winner!.name, testMatch.winner!.name); expect(game.winner!.name, testGame.winner!.name);
expect(match.winner!.createdAt, testMatch.winner!.createdAt); expect(game.winner!.createdAt, testGame.winner!.createdAt);
} else { } else {
expect(match.winner, testMatch.winner); expect(game.winner, testGame.winner);
} }
// Group-Checks // Group-Checks
if (testMatch.group != null) { if (testGame.group != null) {
expect(match.group!.id, testMatch.group!.id); expect(game.group!.id, testGame.group!.id);
expect(match.group!.name, testMatch.group!.name); expect(game.group!.name, testGame.group!.name);
expect(match.group!.createdAt, testMatch.group!.createdAt); expect(game.group!.createdAt, testGame.group!.createdAt);
// Group Members-Checks // Group Members-Checks
expect(match.group!.members.length, testMatch.group!.members.length); expect(game.group!.members.length, testGame.group!.members.length);
for (int i = 0; i < testMatch.group!.members.length; i++) { for (int i = 0; i < testGame.group!.members.length; i++) {
expect(match.group!.members[i].id, testMatch.group!.members[i].id); expect(game.group!.members[i].id, testGame.group!.members[i].id);
expect( expect(
match.group!.members[i].name, game.group!.members[i].name,
testMatch.group!.members[i].name, testGame.group!.members[i].name,
); );
expect( expect(
match.group!.members[i].createdAt, game.group!.members[i].createdAt,
testMatch.group!.members[i].createdAt, testGame.group!.members[i].createdAt,
); );
} }
} else { } else {
expect(match.group, null); expect(game.group, null);
} }
// Players-Checks // Players-Checks
if (testMatch.players != null) { if (testGame.players != null) {
expect(match.players!.length, testMatch.players!.length); expect(game.players!.length, testGame.players!.length);
for (int i = 0; i < testMatch.players!.length; i++) { for (int i = 0; i < testGame.players!.length; i++) {
expect(match.players![i].id, testMatch.players![i].id); expect(game.players![i].id, testGame.players![i].id);
expect(match.players![i].name, testMatch.players![i].name); expect(game.players![i].name, testGame.players![i].name);
expect( expect(game.players![i].createdAt, testGame.players![i].createdAt);
match.players![i].createdAt,
testMatch.players![i].createdAt,
);
} }
} else { } else {
expect(match.players, null); expect(game.players, null);
} }
} }
}); });
test('Adding the same match twice does not create duplicates', () async { test('Adding the same game twice does not create duplicates', () async {
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
final matchCount = await database.matchDao.getMatchCount(); final gameCount = await database.gameDao.getGameCount();
expect(matchCount, 1); expect(gameCount, 1);
}); });
test('Match existence check works correctly', () async { test('Game existence check works correctly', () async {
var matchExists = await database.matchDao.matchExists( var gameExists = await database.gameDao.gameExists(gameId: testGame1.id);
matchId: testMatch1.id, expect(gameExists, false);
await database.gameDao.addGame(game: testGame1);
gameExists = await database.gameDao.gameExists(gameId: testGame1.id);
expect(gameExists, true);
});
test('Deleting a game works correctly', () async {
await database.gameDao.addGame(game: testGame1);
final gameDeleted = await database.gameDao.deleteGame(
gameId: testGame1.id,
); );
expect(matchExists, false); expect(gameDeleted, true);
await database.matchDao.addMatch(match: testMatch1); final gameExists = await database.gameDao.gameExists(
gameId: testGame1.id,
matchExists = await database.matchDao.matchExists(matchId: testMatch1.id);
expect(matchExists, true);
});
test('Deleting a match works correctly', () async {
await database.matchDao.addMatch(match: testMatch1);
final matchDeleted = await database.matchDao.deleteMatch(
matchId: testMatch1.id,
); );
expect(matchDeleted, true); expect(gameExists, false);
final matchExists = await database.matchDao.matchExists(
matchId: testMatch1.id,
);
expect(matchExists, false);
}); });
test('Getting the match count works correctly', () async { test('Getting the game count works correctly', () async {
var matchCount = await database.matchDao.getMatchCount(); var gameCount = await database.gameDao.getGameCount();
expect(matchCount, 0); expect(gameCount, 0);
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
matchCount = await database.matchDao.getMatchCount(); gameCount = await database.gameDao.getGameCount();
expect(matchCount, 1); expect(gameCount, 1);
await database.matchDao.addMatch(match: testMatch2); await database.gameDao.addGame(game: testGame2);
matchCount = await database.matchDao.getMatchCount(); gameCount = await database.gameDao.getGameCount();
expect(matchCount, 2); expect(gameCount, 2);
await database.matchDao.deleteMatch(matchId: testMatch1.id); await database.gameDao.deleteGame(gameId: testGame1.id);
matchCount = await database.matchDao.getMatchCount(); gameCount = await database.gameDao.getGameCount();
expect(matchCount, 1); expect(gameCount, 1);
await database.matchDao.deleteMatch(matchId: testMatch2.id); await database.gameDao.deleteGame(gameId: testGame2.id);
matchCount = await database.matchDao.getMatchCount(); gameCount = await database.gameDao.getGameCount();
expect(matchCount, 0); expect(gameCount, 0);
}); });
test('Checking if match has winner works correctly', () async { test('Checking if game has winner works correclty', () async {
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
await database.matchDao.addMatch(match: testMatchOnlyGroup); await database.gameDao.addGame(game: testGameOnlyGroup);
var hasWinner = await database.matchDao.hasWinner(matchId: testMatch1.id); var hasWinner = await database.gameDao.hasWinner(gameId: testGame1.id);
expect(hasWinner, true); expect(hasWinner, true);
hasWinner = await database.matchDao.hasWinner( hasWinner = await database.gameDao.hasWinner(
matchId: testMatchOnlyGroup.id, gameId: testGameOnlyGroup.id,
); );
expect(hasWinner, false); expect(hasWinner, false);
}); });
test('Fetching the winner of a match works correctly', () async { test('Fetching the winner of a game works correctly', () async {
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
final winner = await database.matchDao.getWinner(matchId: testMatch1.id); final winner = await database.gameDao.getWinner(gameId: testGame1.id);
if (winner == null) { if (winner == null) {
fail('Winner is null'); fail('Winner is null');
} else { } else {
expect(winner.id, testMatch1.winner!.id); expect(winner.id, testGame1.winner!.id);
expect(winner.name, testMatch1.winner!.name); expect(winner.name, testGame1.winner!.name);
expect(winner.createdAt, testMatch1.winner!.createdAt); expect(winner.createdAt, testGame1.winner!.createdAt);
} }
}); });
test('Updating the winner of a match works correctly', () async { test('Updating the winner of a game works correctly', () async {
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
final winner = await database.matchDao.getWinner(matchId: testMatch1.id); final winner = await database.gameDao.getWinner(gameId: testGame1.id);
if (winner == null) { if (winner == null) {
fail('Winner is null'); fail('Winner is null');
} else { } else {
expect(winner.id, testMatch1.winner!.id); expect(winner.id, testGame1.winner!.id);
expect(winner.name, testMatch1.winner!.name); expect(winner.name, testGame1.winner!.name);
expect(winner.createdAt, testMatch1.winner!.createdAt); expect(winner.createdAt, testGame1.winner!.createdAt);
expect(winner.id, testPlayer4.id); expect(winner.id, testPlayer4.id);
expect(winner.id != testPlayer5.id, true); expect(winner.id != testPlayer5.id, true);
} }
await database.matchDao.setWinner( await database.gameDao.setWinner(
matchId: testMatch1.id, gameId: testGame1.id,
winnerId: testPlayer5.id, winnerId: testPlayer5.id,
); );
final newWinner = await database.matchDao.getWinner( final newWinner = await database.gameDao.getWinner(gameId: testGame1.id);
matchId: testMatch1.id,
);
if (newWinner == null) { if (newWinner == null) {
fail('New winner is null'); fail('New winner is null');
@@ -322,41 +292,39 @@ void main() {
}); });
test('Removing a winner works correctly', () async { test('Removing a winner works correctly', () async {
await database.matchDao.addMatch(match: testMatch2); await database.gameDao.addGame(game: testGame2);
var hasWinner = await database.matchDao.hasWinner(matchId: testMatch2.id); var hasWinner = await database.gameDao.hasWinner(gameId: testGame2.id);
expect(hasWinner, true); expect(hasWinner, true);
await database.matchDao.removeWinner(matchId: testMatch2.id); await database.gameDao.removeWinner(gameId: testGame2.id);
hasWinner = await database.matchDao.hasWinner(matchId: testMatch2.id); hasWinner = await database.gameDao.hasWinner(gameId: testGame2.id);
expect(hasWinner, false); expect(hasWinner, false);
final removedWinner = await database.matchDao.getWinner( final removedWinner = await database.gameDao.getWinner(
matchId: testMatch2.id, gameId: testGame2.id,
); );
expect(removedWinner, null); expect(removedWinner, null);
}); });
test('Renaming a match works correctly', () async { test('Renaming a game works correctly', () async {
await database.matchDao.addMatch(match: testMatch1); await database.gameDao.addGame(game: testGame1);
var fetchedMatch = await database.matchDao.getMatchById( var fetchedGame = await database.gameDao.getGameById(
matchId: testMatch1.id, gameId: testGame1.id,
); );
expect(fetchedMatch.name, testMatch1.name); expect(fetchedGame.name, testGame1.name);
const newName = 'Updated Match Name'; const newName = 'Updated Game Name';
await database.matchDao.updateMatchName( await database.gameDao.updateGameName(
matchId: testMatch1.id, gameId: testGame1.id,
newName: newName, newName: newName,
); );
fetchedMatch = await database.matchDao.getMatchById( fetchedGame = await database.gameDao.getGameById(gameId: testGame1.id);
matchId: testMatch1.id, expect(fetchedGame.name, newName);
);
expect(fetchedMatch.name, newName);
}); });
}); });
} }

View File

@@ -1,10 +1,10 @@
import 'package:clock/clock.dart'; import 'package:clock/clock.dart';
import 'package:drift/drift.dart' hide isNotNull; import 'package:drift/drift.dart';
import 'package:drift/native.dart'; import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:game_tracker/data/db/database.dart'; import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart'; import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart'; import 'package:game_tracker/data/dto/player.dart';
void main() { void main() {
@@ -16,12 +16,12 @@ void main() {
late Player testPlayer5; late Player testPlayer5;
late Group testGroup1; late Group testGroup1;
late Group testGroup2; late Group testGroup2;
late Match testMatchWithGroup; late Game testgameWithGroup;
late Match testMatchWithPlayers; late Game testgameWithPlayers;
final fixedDate = DateTime(2025, 19, 11, 00, 11, 23); final fixedDate = DateTime(2025, 19, 11, 00, 11, 23);
final fakeClock = Clock(() => fixedDate); final fakeClock = Clock(() => fixedDate);
setUp(() async { setUp(() {
database = AppDatabase( database = AppDatabase(
DatabaseConnection( DatabaseConnection(
NativeDatabase.memory(), NativeDatabase.memory(),
@@ -44,94 +44,81 @@ void main() {
name: 'Test Group', name: 'Test Group',
members: [testPlayer3, testPlayer2], members: [testPlayer3, testPlayer2],
); );
testMatchWithPlayers = Match( testgameWithPlayers = Game(
name: 'Test Match with Players', name: 'Test Game with Players',
players: [testPlayer4, testPlayer5], players: [testPlayer4, testPlayer5],
); );
testMatchWithGroup = Match( testgameWithGroup = Game(name: 'Test Game with Group', group: testGroup1);
name: 'Test Match with Group',
group: testGroup1,
);
}); });
await database.playerDao.addPlayersAsList(
players: [
testPlayer1,
testPlayer2,
testPlayer3,
testPlayer4,
testPlayer5,
],
);
await database.groupDao.addGroupsAsList(groups: [testGroup1, testGroup2]);
}); });
tearDown(() async { tearDown(() async {
await database.close(); await database.close();
}); });
group('Group-Match Tests', () { group('Group-Game Tests', () {
test('matchHasGroup() has group works correctly', () async { test('Game has group works correctly', () async {
await database.matchDao.addMatch(match: testMatchWithPlayers); await database.gameDao.addGame(game: testgameWithPlayers);
await database.groupDao.addGroup(group: testGroup1); await database.groupDao.addGroup(group: testGroup1);
var matchHasGroup = await database.groupMatchDao.matchHasGroup( var gameHasGroup = await database.groupGameDao.gameHasGroup(
matchId: testMatchWithPlayers.id, gameId: testgameWithPlayers.id,
); );
expect(matchHasGroup, false); expect(gameHasGroup, false);
await database.groupMatchDao.addGroupToMatch( await database.groupGameDao.addGroupToGame(
matchId: testMatchWithPlayers.id, gameId: testgameWithPlayers.id,
groupId: testGroup1.id, groupId: testGroup1.id,
); );
matchHasGroup = await database.groupMatchDao.matchHasGroup( gameHasGroup = await database.groupGameDao.gameHasGroup(
matchId: testMatchWithPlayers.id, gameId: testgameWithPlayers.id,
); );
expect(matchHasGroup, true); expect(gameHasGroup, true);
}); });
test('Adding a group to a match works correctly', () async { test('Adding a group to a game works correctly', () async {
await database.matchDao.addMatch(match: testMatchWithPlayers); await database.gameDao.addGame(game: testgameWithPlayers);
await database.groupDao.addGroup(group: testGroup1); await database.groupDao.addGroup(group: testGroup1);
await database.groupMatchDao.addGroupToMatch( await database.groupGameDao.addGroupToGame(
matchId: testMatchWithPlayers.id, gameId: testgameWithPlayers.id,
groupId: testGroup1.id, groupId: testGroup1.id,
); );
var groupAdded = await database.groupMatchDao.isGroupInMatch( var groupAdded = await database.groupGameDao.isGroupInGame(
matchId: testMatchWithPlayers.id, gameId: testgameWithPlayers.id,
groupId: testGroup1.id, groupId: testGroup1.id,
); );
expect(groupAdded, true); expect(groupAdded, true);
groupAdded = await database.groupMatchDao.isGroupInMatch( groupAdded = await database.groupGameDao.isGroupInGame(
matchId: testMatchWithPlayers.id, gameId: testgameWithPlayers.id,
groupId: '', groupId: '',
); );
expect(groupAdded, false); expect(groupAdded, false);
}); });
test('Removing group from match works correctly', () async { test('Removing group from game works correctly', () async {
await database.matchDao.addMatch(match: testMatchWithGroup); await database.gameDao.addGame(game: testgameWithGroup);
final groupToRemove = testMatchWithGroup.group!; final groupToRemove = testgameWithGroup.group!;
final removed = await database.groupMatchDao.removeGroupFromMatch( final removed = await database.groupGameDao.removeGroupFromGame(
groupId: groupToRemove.id, groupId: groupToRemove.id,
matchId: testMatchWithGroup.id, gameId: testgameWithGroup.id,
); );
expect(removed, true); expect(removed, true);
final result = await database.matchDao.getMatchById( final result = await database.gameDao.getGameById(
matchId: testMatchWithGroup.id, gameId: testgameWithGroup.id,
); );
expect(result.group, null); expect(result.group, null);
}); });
test('Retrieving group of a match works correctly', () async { test('Retrieving group of a game works correctly', () async {
await database.matchDao.addMatch(match: testMatchWithGroup); await database.gameDao.addGame(game: testgameWithGroup);
final group = await database.groupMatchDao.getGroupOfMatch( final group = await database.groupGameDao.getGroupOfGame(
matchId: testMatchWithGroup.id, gameId: testgameWithGroup.id,
); );
if (group == null) { if (group == null) {
@@ -149,11 +136,11 @@ void main() {
} }
}); });
test('Updating the group of a match works correctly', () async { test('Updating the group of a game works correctly', () async {
await database.matchDao.addMatch(match: testMatchWithGroup); await database.gameDao.addGame(game: testgameWithGroup);
var group = await database.groupMatchDao.getGroupOfMatch( var group = await database.groupGameDao.getGroupOfGame(
matchId: testMatchWithGroup.id, gameId: testgameWithGroup.id,
); );
if (group == null) { if (group == null) {
@@ -166,13 +153,13 @@ void main() {
} }
await database.groupDao.addGroup(group: testGroup2); await database.groupDao.addGroup(group: testGroup2);
await database.groupMatchDao.updateGroupOfMatch( await database.groupGameDao.updateGroupOfGame(
matchId: testMatchWithGroup.id, gameId: testgameWithGroup.id,
newGroupId: testGroup2.id, newGroupId: testGroup2.id,
); );
group = await database.groupMatchDao.getGroupOfMatch( group = await database.groupGameDao.getGroupOfGame(
matchId: testMatchWithGroup.id, gameId: testgameWithGroup.id,
); );
if (group == null) { if (group == null) {
@@ -189,33 +176,5 @@ void main() {
} }
} }
}); });
test('Adding the same group to seperate matches works correctly', () async {
final match1 = Match(name: 'Match 1', group: testGroup1);
final match2 = Match(name: 'Match 2', group: testGroup1);
await Future.wait([
database.matchDao.addMatch(match: match1),
database.matchDao.addMatch(match: match2),
]);
final group1 = await database.groupMatchDao.getGroupOfMatch(
matchId: match1.id,
);
final group2 = await database.groupMatchDao.getGroupOfMatch(
matchId: match2.id,
);
expect(group1, isNotNull);
expect(group2, isNotNull);
final groups = [group1!, group2!];
for (final group in groups) {
expect(group.members.length, testGroup1.members.length);
expect(group.id, testGroup1.id);
expect(group.name, testGroup1.name);
expect(group.createdAt, testGroup1.createdAt);
}
});
}); });
} }

View File

@@ -0,0 +1,183 @@
import 'package:clock/clock.dart';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/game.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/player.dart';
void main() {
late AppDatabase database;
late Player testPlayer1;
late Player testPlayer2;
late Player testPlayer3;
late Player testPlayer4;
late Player testPlayer5;
late Player testPlayer6;
late Group testgroup;
late Game testGameOnlyGroup;
late Game testGameOnlyPlayers;
final fixedDate = DateTime(2025, 19, 11, 00, 11, 23);
final fakeClock = Clock(() => fixedDate);
setUp(() {
database = AppDatabase(
DatabaseConnection(
NativeDatabase.memory(),
// Recommended for widget tests to avoid test errors.
closeStreamsSynchronously: true,
),
);
withClock(fakeClock, () {
testPlayer1 = Player(name: 'Alice');
testPlayer2 = Player(name: 'Bob');
testPlayer3 = Player(name: 'Charlie');
testPlayer4 = Player(name: 'Diana');
testPlayer5 = Player(name: 'Eve');
testPlayer6 = Player(name: 'Frank');
testgroup = Group(
name: 'Test Group',
members: [testPlayer1, testPlayer2, testPlayer3],
);
testGameOnlyGroup = Game(name: 'Test Game with Group', group: testgroup);
testGameOnlyPlayers = Game(
name: 'Test Game with Players',
players: [testPlayer4, testPlayer5, testPlayer6],
);
});
});
tearDown(() async {
await database.close();
});
group('Player-Game Tests', () {
test('Game has player works correctly', () async {
await database.gameDao.addGame(game: testGameOnlyGroup);
await database.playerDao.addPlayer(player: testPlayer1);
var gameHasPlayers = await database.playerGameDao.gameHasPlayers(
gameId: testGameOnlyGroup.id,
);
expect(gameHasPlayers, false);
await database.playerGameDao.addPlayerToGame(
gameId: testGameOnlyGroup.id,
playerId: testPlayer1.id,
);
gameHasPlayers = await database.playerGameDao.gameHasPlayers(
gameId: testGameOnlyGroup.id,
);
expect(gameHasPlayers, true);
});
test('Adding a player to a game works correctly', () async {
await database.gameDao.addGame(game: testGameOnlyGroup);
await database.playerDao.addPlayer(player: testPlayer5);
await database.playerGameDao.addPlayerToGame(
gameId: testGameOnlyGroup.id,
playerId: testPlayer5.id,
);
var playerAdded = await database.playerGameDao.isPlayerInGame(
gameId: testGameOnlyGroup.id,
playerId: testPlayer5.id,
);
expect(playerAdded, true);
playerAdded = await database.playerGameDao.isPlayerInGame(
gameId: testGameOnlyGroup.id,
playerId: '',
);
expect(playerAdded, false);
});
test('Removing player from game works correctly', () async {
await database.gameDao.addGame(game: testGameOnlyPlayers);
final playerToRemove = testGameOnlyPlayers.players![0];
final removed = await database.playerGameDao.removePlayerFromGame(
playerId: playerToRemove.id,
gameId: testGameOnlyPlayers.id,
);
expect(removed, true);
final result = await database.gameDao.getGameById(
gameId: testGameOnlyPlayers.id,
);
expect(result.players!.length, testGameOnlyPlayers.players!.length - 1);
final playerExists = result.players!.any(
(p) => p.id == playerToRemove.id,
);
expect(playerExists, false);
});
test('Retrieving players of a game works correctly', () async {
await database.gameDao.addGame(game: testGameOnlyPlayers);
final players = await database.playerGameDao.getPlayersOfGame(
gameId: testGameOnlyPlayers.id,
);
if (players == null) {
fail('Players should not be null');
}
for (int i = 0; i < players.length; i++) {
expect(players[i].id, testGameOnlyPlayers.players![i].id);
expect(players[i].name, testGameOnlyPlayers.players![i].name);
expect(players[i].createdAt, testGameOnlyPlayers.players![i].createdAt);
}
});
test('Updating the games players works coreclty', () async {
await database.gameDao.addGame(game: testGameOnlyPlayers);
final newPlayers = [testPlayer1, testPlayer2, testPlayer4];
await database.playerDao.addPlayersAsList(players: newPlayers);
// First, remove all existing players
final existingPlayers = await database.playerGameDao.getPlayersOfGame(
gameId: testGameOnlyPlayers.id,
);
if (existingPlayers == null || existingPlayers.isEmpty) {
fail('Existing players should not be null or empty');
}
await database.playerGameDao.updatePlayersFromGame(
gameId: testGameOnlyPlayers.id,
newPlayer: newPlayers,
);
final updatedPlayers = await database.playerGameDao.getPlayersOfGame(
gameId: testGameOnlyPlayers.id,
);
if (updatedPlayers == null) {
fail('Updated players should not be null');
}
expect(updatedPlayers.length, newPlayers.length);
/// Create a map of new players for easy lookup
final testPlayers = {for (var p in newPlayers) p.id: p};
/// Verify each updated player matches the new players
for (final player in updatedPlayers) {
final testPlayer = testPlayers[player.id]!;
expect(player.id, testPlayer.id);
expect(player.name, testPlayer.name);
expect(player.createdAt, testPlayer.createdAt);
}
});
});
}

View File

@@ -1,237 +0,0 @@
import 'package:clock/clock.dart';
import 'package:drift/drift.dart' hide isNotNull;
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:game_tracker/data/db/database.dart';
import 'package:game_tracker/data/dto/group.dart';
import 'package:game_tracker/data/dto/match.dart';
import 'package:game_tracker/data/dto/player.dart';
void main() {
late AppDatabase database;
late Player testPlayer1;
late Player testPlayer2;
late Player testPlayer3;
late Player testPlayer4;
late Player testPlayer5;
late Player testPlayer6;
late Group testgroup;
late Match testMatchOnlyGroup;
late Match testMatchOnlyPlayers;
final fixedDate = DateTime(2025, 19, 11, 00, 11, 23);
final fakeClock = Clock(() => fixedDate);
setUp(() async {
database = AppDatabase(
DatabaseConnection(
NativeDatabase.memory(),
// Recommended for widget tests to avoid test errors.
closeStreamsSynchronously: true,
),
);
withClock(fakeClock, () {
testPlayer1 = Player(name: 'Alice');
testPlayer2 = Player(name: 'Bob');
testPlayer3 = Player(name: 'Charlie');
testPlayer4 = Player(name: 'Diana');
testPlayer5 = Player(name: 'Eve');
testPlayer6 = Player(name: 'Frank');
testgroup = Group(
name: 'Test Group',
members: [testPlayer1, testPlayer2, testPlayer3],
);
testMatchOnlyGroup = Match(
name: 'Test Match with Group',
group: testgroup,
);
testMatchOnlyPlayers = Match(
name: 'Test Match with Players',
players: [testPlayer4, testPlayer5, testPlayer6],
);
});
await database.playerDao.addPlayersAsList(
players: [
testPlayer1,
testPlayer2,
testPlayer3,
testPlayer4,
testPlayer5,
testPlayer6,
],
);
await database.groupDao.addGroup(group: testgroup);
});
tearDown(() async {
await database.close();
});
group('Player-Match Tests', () {
test('Match has player works correctly', () async {
await database.matchDao.addMatch(match: testMatchOnlyGroup);
await database.playerDao.addPlayer(player: testPlayer1);
var matchHasPlayers = await database.playerMatchDao.matchHasPlayers(
matchId: testMatchOnlyGroup.id,
);
expect(matchHasPlayers, false);
await database.playerMatchDao.addPlayerToMatch(
matchId: testMatchOnlyGroup.id,
playerId: testPlayer1.id,
);
matchHasPlayers = await database.playerMatchDao.matchHasPlayers(
matchId: testMatchOnlyGroup.id,
);
expect(matchHasPlayers, true);
});
test('Adding a player to a match works correctly', () async {
await database.matchDao.addMatch(match: testMatchOnlyGroup);
await database.playerDao.addPlayer(player: testPlayer5);
await database.playerMatchDao.addPlayerToMatch(
matchId: testMatchOnlyGroup.id,
playerId: testPlayer5.id,
);
var playerAdded = await database.playerMatchDao.isPlayerInMatch(
matchId: testMatchOnlyGroup.id,
playerId: testPlayer5.id,
);
expect(playerAdded, true);
playerAdded = await database.playerMatchDao.isPlayerInMatch(
matchId: testMatchOnlyGroup.id,
playerId: '',
);
expect(playerAdded, false);
});
test('Removing player from match works correctly', () async {
await database.matchDao.addMatch(match: testMatchOnlyPlayers);
final playerToRemove = testMatchOnlyPlayers.players![0];
final removed = await database.playerMatchDao.removePlayerFromMatch(
playerId: playerToRemove.id,
matchId: testMatchOnlyPlayers.id,
);
expect(removed, true);
final result = await database.matchDao.getMatchById(
matchId: testMatchOnlyPlayers.id,
);
expect(result.players!.length, testMatchOnlyPlayers.players!.length - 1);
final playerExists = result.players!.any(
(p) => p.id == playerToRemove.id,
);
expect(playerExists, false);
});
test('Retrieving players of a match works correctly', () async {
await database.matchDao.addMatch(match: testMatchOnlyPlayers);
final players = await database.playerMatchDao.getPlayersOfMatch(
matchId: testMatchOnlyPlayers.id,
);
if (players == null) {
fail('Players should not be null');
}
for (int i = 0; i < players.length; i++) {
expect(players[i].id, testMatchOnlyPlayers.players![i].id);
expect(players[i].name, testMatchOnlyPlayers.players![i].name);
expect(
players[i].createdAt,
testMatchOnlyPlayers.players![i].createdAt,
);
}
});
test('Updating the match players works coreclty', () async {
await database.matchDao.addMatch(match: testMatchOnlyPlayers);
final newPlayers = [testPlayer1, testPlayer2, testPlayer4];
await database.playerDao.addPlayersAsList(players: newPlayers);
// First, remove all existing players
final existingPlayers = await database.playerMatchDao.getPlayersOfMatch(
matchId: testMatchOnlyPlayers.id,
);
if (existingPlayers == null || existingPlayers.isEmpty) {
fail('Existing players should not be null or empty');
}
await database.playerMatchDao.updatePlayersFromMatch(
matchId: testMatchOnlyPlayers.id,
newPlayer: newPlayers,
);
final updatedPlayers = await database.playerMatchDao.getPlayersOfMatch(
matchId: testMatchOnlyPlayers.id,
);
if (updatedPlayers == null) {
fail('Updated players should not be null');
}
expect(updatedPlayers.length, newPlayers.length);
/// Create a map of new players for easy lookup
final testPlayers = {for (var p in newPlayers) p.id: p};
/// Verify each updated player matches the new players
for (final player in updatedPlayers) {
final testPlayer = testPlayers[player.id]!;
expect(player.id, testPlayer.id);
expect(player.name, testPlayer.name);
expect(player.createdAt, testPlayer.createdAt);
}
});
test(
'Adding the same player to seperate matches works correctly',
() async {
final playersList = [testPlayer1, testPlayer2, testPlayer3];
final match1 = Match(name: 'Match 1', players: playersList);
final match2 = Match(name: 'Match 2', players: playersList);
await Future.wait([
database.matchDao.addMatch(match: match1),
database.matchDao.addMatch(match: match2),
]);
final players1 = await database.playerMatchDao.getPlayersOfMatch(
matchId: match1.id,
);
final players2 = await database.playerMatchDao.getPlayersOfMatch(
matchId: match2.id,
);
expect(players1, isNotNull);
expect(players2, isNotNull);
expect(
players1!.map((p) => p.id).toList(),
equals(players2!.map((p) => p.id).toList()),
);
expect(
players1.map((p) => p.name).toList(),
equals(players2.map((p) => p.name).toList()),
);
expect(
players1.map((p) => p.createdAt).toList(),
equals(players2.map((p) => p.createdAt).toList()),
);
},
);
});
}