This commit is contained in:
kejaro committed 2026-09-27 21:41:56 +01:00
1 parent 97c10c8d12
commit 212410f716
10 files changed
+1061 -32

No files matched your search

+4 -2
View File
@@ -8,7 +8,9 @@ import 'ui/features/dashboard/views/match_results_view.dart';
import 'ui/features/settings/views/settings_view.dart'; import 'ui/features/settings/views/settings_view.dart';
class MobileApp extends StatefulWidget { class MobileApp extends StatefulWidget {
const MobileApp({super.key}); const MobileApp({super.key, this.matchRepository});
final MatchRepository? matchRepository;
@override @override
State<MobileApp> createState() => _MobileAppState(); State<MobileApp> createState() => _MobileAppState();
@@ -24,7 +26,7 @@ class _MobileAppState extends State<MobileApp> {
super.initState(); super.initState();
_themeController = ThemeController(); _themeController = ThemeController();
_matchResultsViewModel = MatchResultsViewModel( _matchResultsViewModel = MatchResultsViewModel(
repository: MatchRepository(), repository: widget.matchRepository ?? MatchRepository(),
); );
_matchResultsViewModel.loadMatches(); _matchResultsViewModel.loadMatches();
} }
@@ -1,18 +1,68 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import '../../domain/models/hockey_game.dart'; import '../../domain/models/hockey_game.dart';
class MatchRepository { class MatchRepository {
MatchRepository({AssetBundle? bundle}) : _bundle = bundle ?? rootBundle; MatchRepository({
AssetBundle? bundle,
Future<Directory> Function()? documentsDirectoryProvider,
}) : _bundle = bundle ?? rootBundle,
_documentsDirectoryProvider =
documentsDirectoryProvider ?? getApplicationDocumentsDirectory;
final AssetBundle _bundle; final AssetBundle _bundle;
final Future<Directory> Function() _documentsDirectoryProvider;
Future<List<Match>> loadMatches() async { Future<List<Match>> loadSourceMatches() async {
final contents = await _bundle.loadString('lib/data/results.json'); final contents = await _bundle.loadString('lib/data/results.json');
final data = jsonDecode(contents) as Map<String, dynamic>; final data = jsonDecode(contents) as Map<String, dynamic>;
return (data['games'] as List<dynamic>) return (data['games'] as List<dynamic>)
.map((game) => Match.fromJson(game as Map<String, dynamic>)) .map((game) => Match.fromJson(game as Map<String, dynamic>))
.toList(); .toList();
} }
Future<StoredMatchData> loadStoredData() async {
final file = await _storageFile();
if (!await file.exists()) {
return const StoredMatchData(matches: [], sourceCursor: 0);
}
final data = jsonDecode(await file.readAsString()) as Map<String, dynamic>;
final storedMatches = data['matches'] as List<dynamic>? ?? const [];
final sourceCursor = data['sourceCursor'];
return StoredMatchData(
matches: storedMatches
.map((match) => Match.fromJson(match as Map<String, dynamic>))
.toList(),
sourceCursor: sourceCursor is int && sourceCursor >= 0 ? sourceCursor : 0,
);
}
Future<void> saveStoredData(List<Match> matches, int sourceCursor) async {
final file = await _storageFile();
await file.writeAsString(
jsonEncode({
'sourceCursor': sourceCursor,
'matches': matches.map((match) => match.toJson()).toList(),
}),
flush: true,
);
}
Future<File> _storageFile() async {
final directory = await _documentsDirectoryProvider();
await directory.create(recursive: true);
return File('${directory.path}${Platform.pathSeparator}match-results.json');
}
}
class StoredMatchData {
const StoredMatchData({required this.matches, required this.sourceCursor});
final List<Match> matches;
final int sourceCursor;
} }
+720
View File
@@ -37,6 +37,726 @@
"team": 0 "team": 0
} }
] ]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 0,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 2
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"goal_type": 0,
"elapsed": 32,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 2,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"elapsed": 88,
"goal_type": 2,
"team": 1
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"elapsed": 32,
"goal_type": 1,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"elapsed": 66,
"goal_type": 0,
"team": 0
}
]
},
{ "datetime": "2023-10-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 0,
"datetime": "2023-10-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 2,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 0,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 0,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 2
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"goal_type": 0,
"elapsed": 32,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 2,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"elapsed": 88,
"goal_type": 2,
"team": 1
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"elapsed": 32,
"goal_type": 1,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"elapsed": 66,
"goal_type": 0,
"team": 0
}
]
},
{ "datetime": "2023-10-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 0,
"datetime": "2023-10-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 2,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 0,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 0,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 2
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"goal_type": 0,
"elapsed": 32,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 2,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"elapsed": 88,
"goal_type": 2,
"team": 1
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"elapsed": 32,
"goal_type": 1,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"elapsed": 66,
"goal_type": 0,
"team": 0
}
]
},
{ "datetime": "2023-10-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 0,
"datetime": "2023-10-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 2,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 0,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 0,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 2
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"goal_type": 0,
"elapsed": 32,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 2,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"elapsed": 88,
"goal_type": 2,
"team": 1
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"elapsed": 32,
"goal_type": 1,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"elapsed": 66,
"goal_type": 0,
"team": 0
}
]
},
{ "datetime": "2023-10-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 0,
"datetime": "2023-10-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 2,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 0,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 0,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 2
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"goal_type": 0,
"elapsed": 32,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 2,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"elapsed": 88,
"goal_type": 2,
"team": 1
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"elapsed": 32,
"goal_type": 1,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"elapsed": 66,
"goal_type": 0,
"team": 0
}
]
},
{ "datetime": "2023-10-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 0,
"datetime": "2023-10-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 2,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 0,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 0,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 2
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"goal_type": 0,
"elapsed": 32,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 2,
"elapsed": 66,
"team": 0
}
]
},
{ "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 1,
"datetime": "2023-11-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"elapsed": 88,
"goal_type": 2,
"team": 1
},
{
"datetime": "2023-10-01T12:20:00Z",
"player": 32,
"elapsed": 32,
"goal_type": 1,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"elapsed": 66,
"goal_type": 0,
"team": 0
}
]
},
{ "datetime": "2023-10-01T12:00:00Z",
"awayScore": 0,
"homeScore": 1,
"cards": [
{
"card_type": 0,
"datetime": "2023-10-01T12:25:00Z",
"duration": 120,
"player": 5,
"elapsed": 125,
"team": 1
},
{
"card_type": 2,
"datetime": "2023-10-01T12:35:00Z",
"duration": 120,
"player": 8,
"elapsed": 235,
"team": 0
}
],
"goals": [
{
"datetime": "2023-10-01T12:15:00Z",
"player": 32,
"goal_type": 1,
"elapsed": 88,
"team": 1
},
{
"datetime": "2023-10-01T12:30:00Z",
"player": 2,
"goal_type": 0,
"elapsed": 66,
"team": 0
}
]
}, },
{ "datetime": "2023-11-01T12:00:00Z", { "datetime": "2023-11-01T12:00:00Z",
"awayScore": 0, "awayScore": 0,
@@ -0,0 +1,111 @@
import 'dart:async';
import '../../domain/models/hockey_game.dart';
import '../repositories/match_repository.dart';
class MatchDataService {
MatchDataService({
required this.repository,
this.updateInterval = const Duration(seconds: 1),
}) : assert(updateInterval > Duration.zero);
final MatchRepository repository;
final Duration updateInterval;
Timer? _timer;
List<Match> _matches = [];
List<Match> _sourceMatches = [];
int _sourceCursor = 0;
bool _isStarted = false;
bool _isDelivering = false;
bool _isDisposed = false;
Future<void> _writeQueue = Future<void>.value();
void Function(List<Match>)? _onMatchesChanged;
void Function(Object)? _onError;
Future<void> start({
required void Function(List<Match>) onMatchesChanged,
required void Function(Object) onError,
}) async {
if (_isStarted) return;
_isStarted = true;
_onMatchesChanged = onMatchesChanged;
_onError = onError;
final storedData = await repository.loadStoredData();
_matches = List.of(storedData.matches);
_sourceCursor = storedData.sourceCursor;
_notifyMatchesChanged();
_sourceMatches = await repository.loadSourceMatches();
await _deliverNextMatch();
if (_sourceCursor < _sourceMatches.length && !_isDisposed) {
_timer = Timer.periodic(updateInterval, (_) {
unawaited(_deliverNextMatch().catchError(_handleError));
});
}
}
Future<void> removeMatch(Match match) async {
final matchIndex = _matches.indexWhere(
(candidate) => identical(candidate, match),
);
if (matchIndex == -1) return;
final updatedMatches = List<Match>.of(_matches)..removeAt(matchIndex);
_matches = updatedMatches;
_notifyMatchesChanged();
await _persist(updatedMatches, _sourceCursor);
}
Future<void> _deliverNextMatch() async {
if (_isDisposed || _isDelivering || _sourceCursor >= _sourceMatches.length) {
_timer?.cancel();
_timer = null;
return;
}
_isDelivering = true;
try {
final updatedMatches = [..._matches, _sourceMatches[_sourceCursor]];
final nextCursor = _sourceCursor + 1;
await _persist(updatedMatches, nextCursor);
if (_isDisposed) return;
_matches = updatedMatches;
_sourceCursor = nextCursor;
_notifyMatchesChanged();
if (_sourceCursor >= _sourceMatches.length) {
_timer?.cancel();
_timer = null;
}
} finally {
_isDelivering = false;
}
}
Future<void> _persist(List<Match> matches, int sourceCursor) {
final previousWrite = _writeQueue.catchError((Object _) {});
final nextWrite = previousWrite.then(
(_) => repository.saveStoredData(matches, sourceCursor),
);
_writeQueue = nextWrite;
return nextWrite;
}
void _notifyMatchesChanged() {
_onMatchesChanged?.call(List.unmodifiable(_matches));
}
void _handleError(Object error) {
_onError?.call(error);
}
void dispose() {
_isDisposed = true;
_timer?.cancel();
_timer = null;
}
}
@@ -1,11 +1,20 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'dart:async';
import '../../../../data/repositories/match_repository.dart'; import '../../../../data/repositories/match_repository.dart';
import '../../../../data/services/match_data_service.dart';
import '../../../../domain/models/hockey_game.dart'; import '../../../../domain/models/hockey_game.dart';
class MatchResultsViewModel extends ChangeNotifier { class MatchResultsViewModel extends ChangeNotifier {
MatchResultsViewModel({required this.repository}); MatchResultsViewModel({
required MatchRepository repository,
Duration updateInterval = const Duration(seconds: 1),
}) : _dataService = MatchDataService(
repository: repository,
updateInterval: updateInterval,
);
final MatchRepository repository; final MatchDataService _dataService;
List<Match> _matches = []; List<Match> _matches = [];
bool _isLoading = false; bool _isLoading = false;
String? _errorMessage; String? _errorMessage;
@@ -14,13 +23,31 @@ class MatchResultsViewModel extends ChangeNotifier {
bool get isLoading => _isLoading; bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage; String? get errorMessage => _errorMessage;
Future<void> removeMatch(Match match) async {
try {
await _dataService.removeMatch(match);
} catch (_) {
_errorMessage = 'Unable to save match results.';
notifyListeners();
}
}
Future<void> loadMatches() async { Future<void> loadMatches() async {
_isLoading = true; _isLoading = true;
_errorMessage = null; _errorMessage = null;
notifyListeners(); notifyListeners();
try { try {
_matches = await repository.loadMatches(); await _dataService.start(
onMatchesChanged: (matches) {
_matches = matches;
notifyListeners();
},
onError: (_) {
_errorMessage = 'Unable to save match results.';
notifyListeners();
},
);
} catch (error) { } catch (error) {
_errorMessage = 'Unable to load match results.'; _errorMessage = 'Unable to load match results.';
} finally { } finally {
@@ -28,4 +55,10 @@ class MatchResultsViewModel extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
} }
@override
void dispose() {
_dataService.dispose();
super.dispose();
}
} }
@@ -16,21 +16,47 @@ class MatchResultsView extends StatelessWidget {
return ListenableBuilder( return ListenableBuilder(
listenable: viewModel, listenable: viewModel,
builder: (context, _) { builder: (context, _) {
final matches = viewModel.matches;
if (viewModel.isLoading) { if (viewModel.isLoading) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} }
if (viewModel.errorMessage != null) { if (viewModel.errorMessage != null) {
return Center(child: Text(viewModel.errorMessage!)); return Center(child: Text(viewModel.errorMessage!));
} }
if (viewModel.matches.isEmpty) { if (matches.isEmpty) {
return const Center(child: Text('No match results available.')); return const Center(child: Text('No match results available.'));
} }
return ListView.builder( return ListView.builder(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
itemCount: viewModel.matches.length, itemCount: matches.length,
itemBuilder: (context, index) => findChildIndexCallback: (key) {
_MatchCard(match: viewModel.matches[index]), if (key is! ValueKey<Match>) return null;
final index = matches.indexWhere(
(match) => identical(match, key.value),
);
return index == -1 ? null : index;
},
itemBuilder: (context, index) {
final match = matches[index];
return Dismissible(
key: ValueKey(match),
direction: DismissDirection.endToStart,
background: Container(
alignment: Alignment.centerRight,
padding: const EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.delete_outline, color: Colors.white),
),
onDismissed: (_) => viewModel.removeMatch(match),
child: _MatchCard(match: match),
);
},
); );
}, },
); );
@@ -54,10 +80,7 @@ class _MatchCardState extends State<_MatchCard> {
final match = widget.match; final match = widget.match;
final colors = Theme.of(context).colorScheme; final colors = Theme.of(context).colorScheme;
final textTheme = Theme.of(context).textTheme; final textTheme = Theme.of(context).textTheme;
final date = DateTime.tryParse(match.datetime)?.toLocal(); final dateLabel = _exportDate(match.datetime);
final dateLabel = date == null
? match.datetime
: '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
return Card( return Card(
margin: const EdgeInsets.only(bottom: 12), margin: const EdgeInsets.only(bottom: 12),
@@ -245,7 +268,7 @@ String _teamName(Team team) => team == Team.home ? 'Home' : 'Away';
String _matchShareText(Match match) { String _matchShareText(Match match) {
final buffer = StringBuffer() final buffer = StringBuffer()
..writeln('Match result') ..writeln('Match result')
..writeln(match.datetime) ..writeln(_exportDate(match.datetime))
..writeln('Home ${match.homeScore} - ${match.awayScore} Away'); ..writeln('Home ${match.homeScore} - ${match.awayScore} Away');
if (match.goals.isNotEmpty) { if (match.goals.isNotEmpty) {
@@ -277,6 +300,33 @@ String _formatTime(int seconds) {
return '$minute:$second'; return '$minute:$second';
} }
String _exportDate(String rawDateTime) {
final parsed = DateTime.tryParse(rawDateTime)?.toLocal();
if (parsed == null) {
return rawDateTime;
}
final weekday = _weekdayName(parsed.weekday);
final day = parsed.day.toString().padLeft(2, '0');
final month = parsed.month.toString().padLeft(2, '0');
final year = parsed.year.toString().substring(2);
final hour = parsed.hour.toString().padLeft(2, '0');
final minute = parsed.minute.toString().padLeft(2, '0');
return '$weekday $day-$month-$year $hour:$minute';
}
String _weekdayName(int weekday) => switch (weekday) {
DateTime.monday => 'Mon',
DateTime.tuesday => 'Tue',
DateTime.wednesday => 'Wed',
DateTime.thursday => 'Thu',
DateTime.friday => 'Fri',
DateTime.saturday => 'Sat',
DateTime.sunday => 'Sun',
_ => 'Unknown',
};
String _goalTypeName(GoalType type) => switch (type) { String _goalTypeName(GoalType type) => switch (type) {
GoalType.fieldGoal => 'Field goal', GoalType.fieldGoal => 'Field goal',
GoalType.shortCorner => 'Short corner', GoalType.shortCorner => 'Short corner',
+1 -1
View File
@@ -297,7 +297,7 @@ packages:
source: hosted source: hosted
version: "1.1.0" version: "1.1.0"
path_provider: path_provider:
dependency: transitive dependency: "direct main"
description: description:
name: path_provider name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
+1
View File
@@ -32,6 +32,7 @@ dependencies:
sdk: flutter sdk: flutter
flutter_svg: ^2.1.0 flutter_svg: ^2.1.0
path_provider: ^2.1.6
share_plus: ^11.0.0 share_plus: ^11.0.0
# The following adds the Cupertino Icons font to your application. # The following adds the Cupertino Icons font to your application.
@@ -1,3 +1,5 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mobile_app/data/repositories/match_repository.dart'; import 'package:mobile_app/data/repositories/match_repository.dart';
import 'package:mobile_app/ui/features/dashboard/view_models/match_results_view_model.dart'; import 'package:mobile_app/ui/features/dashboard/view_models/match_results_view_model.dart';
@@ -6,18 +8,58 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized(); TestWidgetsFlutterBinding.ensureInitialized();
test('loads match results and their events from bundled JSON', () async { test('loads match results and their events from bundled JSON', () async {
final viewModel = MatchResultsViewModel(repository: MatchRepository()); final matches = await MatchRepository().loadSourceMatches();
expect(matches, hasLength(21));
expect(matches.first.homeScore, 1);
expect(matches.first.goals, hasLength(2));
expect(matches.first.goals.first.seconds, 88);
expect(matches.first.goals.first.team.name, 'away');
expect(matches.first.cards.first.cardType.name, 'red');
});
test('simulates periodic receipt and persists received matches', () async {
final directory = await Directory.systemTemp.createTemp('match-results-');
addTearDown(() => directory.delete(recursive: true));
final repository = MatchRepository(
documentsDirectoryProvider: () async => directory,
);
final viewModel = MatchResultsViewModel(
repository: repository,
updateInterval: const Duration(milliseconds: 10),
);
addTearDown(viewModel.dispose);
await viewModel.loadMatches();
expect(viewModel.matches, hasLength(1));
await Future<void>.delayed(const Duration(milliseconds: 30));
expect(viewModel.matches.length, greaterThan(1));
final storedData = await repository.loadStoredData();
expect(storedData.matches, hasLength(viewModel.matches.length));
expect(storedData.sourceCursor, viewModel.matches.length);
});
test('resumes simulation from the persisted source cursor', () async {
final directory = await Directory.systemTemp.createTemp('match-results-');
addTearDown(() => directory.delete(recursive: true));
final repository = MatchRepository(
documentsDirectoryProvider: () async => directory,
);
final sourceMatches = await repository.loadSourceMatches();
await repository.saveStoredData([sourceMatches.first], 1);
final viewModel = MatchResultsViewModel(
repository: repository,
updateInterval: const Duration(hours: 1),
);
addTearDown(viewModel.dispose); addTearDown(viewModel.dispose);
await viewModel.loadMatches(); await viewModel.loadMatches();
expect(viewModel.isLoading, isFalse); expect(viewModel.matches, hasLength(2));
expect(viewModel.errorMessage, isNull); expect(viewModel.matches.first.datetime, sourceMatches.first.datetime);
expect(viewModel.matches, hasLength(3)); expect(viewModel.matches.last.datetime, sourceMatches[1].datetime);
expect(viewModel.matches.first.homeScore, 1); expect((await repository.loadStoredData()).sourceCursor, 2);
expect(viewModel.matches.first.goals, hasLength(2));
expect(viewModel.matches.first.goals.first.seconds, 88);
expect(viewModel.matches.first.goals.first.team.name, 'away');
expect(viewModel.matches.first.cards.first.cardType.name, 'red');
}); });
} }
+26 -6
View File
@@ -1,30 +1,41 @@
import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mobile_app/app.dart'; import 'package:mobile_app/app.dart';
import 'package:mobile_app/data/repositories/match_repository.dart';
void main() { void main() {
testWidgets('App smoke test - renders match results, navigates to settings', ( testWidgets('App smoke test - renders match results, navigates to settings', (
WidgetTester tester, WidgetTester tester,
) async { ) async {
await tester.pumpWidget(const MobileApp()); final directory = await Directory.systemTemp.createTemp('match-results-');
addTearDown(() => directory.delete(recursive: true));
await tester.pumpWidget(
MobileApp(
matchRepository: MatchRepository(
documentsDirectoryProvider: () async => directory,
),
),
);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Match Results'), findsOneWidget); expect(find.text('Match Results'), findsOneWidget);
expect(find.text('Home'), findsWidgets); expect(find.text('Home'), findsWidgets);
expect(find.text('Away'), findsWidgets); expect(find.text('Away'), findsWidgets);
expect( expect(
find.textContaining(RegExp(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}')), find.textContaining(RegExp(r'[A-Z][a-z]{2} \d{2}-\d{2}-\d{2} \d{2}:\d{2}')),
findsWidgets, findsWidgets,
); );
expect(find.text('Field goal · Away · #32'), findsNothing); expect(find.byType(ExpansionTile), findsWidgets);
await tester.tap( await tester.tap(
find.textContaining(RegExp(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}')).first, find.textContaining(RegExp(r'[A-Z][a-z]{2} \d{2}-\d{2}-\d{2} \d{2}:\d{2}')).first,
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Field goal · Away · #32'), findsWidgets); expect(find.text('Field goal'), findsWidgets);
expect(find.textContaining('card · Away · #5 · 120s'), findsWidgets); expect(find.text('Away'), findsWidgets);
expect(find.byType(Divider), findsNothing); expect(find.byType(Divider), findsNothing);
final matchTile = tester.widget<ExpansionTile>( final matchTile = tester.widget<ExpansionTile>(
find.byType(ExpansionTile).first, find.byType(ExpansionTile).first,
@@ -49,5 +60,14 @@ void main() {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Match Results'), findsOneWidget); expect(find.text('Match Results'), findsOneWidget);
final firstMatchFinder = find.byType(Dismissible).first;
final firstMatch = tester.widget<Dismissible>(firstMatchFinder);
final firstMatchKey = firstMatch.key;
await tester.fling(firstMatchFinder, const Offset(-600, 0), 1000);
await tester.pumpAndSettle();
expect(find.byKey(firstMatchKey!), findsNothing);
}); });
} }