diff --git a/data/.flutter-plugins b/data/.flutter-plugins index a0dd3554..c8f414da 100644 --- a/data/.flutter-plugins +++ b/data/.flutter-plugins @@ -1,14 +1,14 @@ # This is a generated file; do not edit or check into version control. -cloud_firestore=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.0/ -cloud_firestore_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore_web-4.0.0/ +cloud_firestore=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.2/ +cloud_firestore_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore_web-4.0.2/ device_info_plus=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/ -firebase_auth=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.0.0/ -firebase_auth_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth_web-5.12.1/ -firebase_core=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.0.0/ -firebase_core_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core_web-2.17.1/ -firebase_storage=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.0.0/ -firebase_storage_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage_web-3.9.8/ -flutter_timezone=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-1.0.8/ +firebase_auth=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.1.1/ +firebase_auth_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth_web-5.12.3/ +firebase_core=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.1.1/ +firebase_core_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core_web-2.17.2/ +firebase_storage=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.1.0/ +firebase_storage_web=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage_web-3.9.10/ +flutter_timezone=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-2.0.0/ package_info_plus=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/ path_provider_linux=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/ path_provider_windows=/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/ diff --git a/data/.flutter-plugins-dependencies b/data/.flutter-plugins-dependencies index 73aae2b2..65422cb8 100644 --- a/data/.flutter-plugins-dependencies +++ b/data/.flutter-plugins-dependencies @@ -1 +1 @@ -{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":true,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.0.0/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-1.0.8/","native_build":true,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":true,"dependencies":[]},{"name":"shared_preferences_foundation","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_foundation-2.4.0/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"android":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":true,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.0.0/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-1.0.8/","native_build":true,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":true,"dependencies":[]},{"name":"shared_preferences_android","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_android-2.2.3/","native_build":true,"dependencies":[]}],"macos":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":true,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.0.0/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-1.0.8/","native_build":true,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":true,"dependencies":[]},{"name":"shared_preferences_foundation","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_foundation-2.4.0/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"linux":[{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":false,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":false,"dependencies":[]},{"name":"path_provider_linux","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/","native_build":false,"dependencies":[]},{"name":"shared_preferences_linux","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_linux-2.3.2/","native_build":false,"dependencies":["path_provider_linux"]}],"windows":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":false,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.0.0/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.0.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":false,"dependencies":[]},{"name":"path_provider_windows","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/","native_build":false,"dependencies":[]},{"name":"shared_preferences_windows","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_windows-2.3.2/","native_build":false,"dependencies":["path_provider_windows"]}],"web":[{"name":"cloud_firestore_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore_web-4.0.0/","dependencies":["firebase_core_web"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","dependencies":[]},{"name":"firebase_auth_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth_web-5.12.1/","dependencies":["firebase_core_web"]},{"name":"firebase_core_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core_web-2.17.1/","dependencies":[]},{"name":"firebase_storage_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage_web-3.9.8/","dependencies":["firebase_core_web"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-1.0.8/","dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","dependencies":[]},{"name":"shared_preferences_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_web-2.3.0/","dependencies":[]}]},"dependencyGraph":[{"name":"cloud_firestore","dependencies":["cloud_firestore_web","firebase_core"]},{"name":"cloud_firestore_web","dependencies":["firebase_core","firebase_core_web"]},{"name":"device_info_plus","dependencies":[]},{"name":"firebase_auth","dependencies":["firebase_auth_web","firebase_core"]},{"name":"firebase_auth_web","dependencies":["firebase_core","firebase_core_web"]},{"name":"firebase_core","dependencies":["firebase_core_web"]},{"name":"firebase_core_web","dependencies":[]},{"name":"firebase_storage","dependencies":["firebase_core","firebase_storage_web"]},{"name":"firebase_storage_web","dependencies":["firebase_core","firebase_core_web"]},{"name":"flutter_timezone","dependencies":[]},{"name":"package_info_plus","dependencies":[]},{"name":"path_provider_linux","dependencies":[]},{"name":"path_provider_windows","dependencies":[]},{"name":"shared_preferences","dependencies":["shared_preferences_android","shared_preferences_foundation","shared_preferences_linux","shared_preferences_web","shared_preferences_windows"]},{"name":"shared_preferences_android","dependencies":[]},{"name":"shared_preferences_foundation","dependencies":[]},{"name":"shared_preferences_linux","dependencies":["path_provider_linux"]},{"name":"shared_preferences_web","dependencies":[]},{"name":"shared_preferences_windows","dependencies":["path_provider_windows"]}],"date_created":"2024-07-03 17:39:13.100231","version":"3.22.2"} \ No newline at end of file +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.2/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":true,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.1.1/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.1.1/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.1.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-2.0.0/","native_build":true,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":true,"dependencies":[]},{"name":"shared_preferences_foundation","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_foundation-2.4.0/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"android":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.2/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":true,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.1.1/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.1.1/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.1.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-2.0.0/","native_build":true,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":true,"dependencies":[]},{"name":"shared_preferences_android","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_android-2.2.3/","native_build":true,"dependencies":[]}],"macos":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.2/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":true,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.1.1/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.1.1/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.1.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-2.0.0/","native_build":true,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":true,"dependencies":[]},{"name":"shared_preferences_foundation","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_foundation-2.4.0/","shared_darwin_source":true,"native_build":true,"dependencies":[]}],"linux":[{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":false,"dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":false,"dependencies":[]},{"name":"path_provider_linux","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/path_provider_linux-2.2.1/","native_build":false,"dependencies":[]},{"name":"shared_preferences_linux","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_linux-2.3.2/","native_build":false,"dependencies":["path_provider_linux"]}],"windows":[{"name":"cloud_firestore","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore-5.0.2/","native_build":true,"dependencies":["firebase_core"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","native_build":false,"dependencies":[]},{"name":"firebase_auth","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth-5.1.1/","native_build":true,"dependencies":["firebase_core"]},{"name":"firebase_core","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core-3.1.1/","native_build":true,"dependencies":[]},{"name":"firebase_storage","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage-12.1.0/","native_build":true,"dependencies":["firebase_core"]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","native_build":false,"dependencies":[]},{"name":"path_provider_windows","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/path_provider_windows-2.2.1/","native_build":false,"dependencies":[]},{"name":"shared_preferences_windows","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_windows-2.3.2/","native_build":false,"dependencies":["path_provider_windows"]}],"web":[{"name":"cloud_firestore_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/cloud_firestore_web-4.0.2/","dependencies":["firebase_core_web"]},{"name":"device_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/device_info_plus-10.1.0/","dependencies":[]},{"name":"firebase_auth_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_auth_web-5.12.3/","dependencies":["firebase_core_web"]},{"name":"firebase_core_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_core_web-2.17.2/","dependencies":[]},{"name":"firebase_storage_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/firebase_storage_web-3.9.10/","dependencies":["firebase_core_web"]},{"name":"flutter_timezone","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/flutter_timezone-2.0.0/","dependencies":[]},{"name":"package_info_plus","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/package_info_plus-8.0.0/","dependencies":[]},{"name":"shared_preferences_web","path":"/Users/sidhdhi.p/.pub-cache/hosted/pub.dev/shared_preferences_web-2.3.0/","dependencies":[]}]},"dependencyGraph":[{"name":"cloud_firestore","dependencies":["cloud_firestore_web","firebase_core"]},{"name":"cloud_firestore_web","dependencies":["firebase_core","firebase_core_web"]},{"name":"device_info_plus","dependencies":[]},{"name":"firebase_auth","dependencies":["firebase_auth_web","firebase_core"]},{"name":"firebase_auth_web","dependencies":["firebase_core","firebase_core_web"]},{"name":"firebase_core","dependencies":["firebase_core_web"]},{"name":"firebase_core_web","dependencies":[]},{"name":"firebase_storage","dependencies":["firebase_core","firebase_storage_web"]},{"name":"firebase_storage_web","dependencies":["firebase_core","firebase_core_web"]},{"name":"flutter_timezone","dependencies":[]},{"name":"package_info_plus","dependencies":[]},{"name":"path_provider_linux","dependencies":[]},{"name":"path_provider_windows","dependencies":[]},{"name":"shared_preferences","dependencies":["shared_preferences_android","shared_preferences_foundation","shared_preferences_linux","shared_preferences_web","shared_preferences_windows"]},{"name":"shared_preferences_android","dependencies":[]},{"name":"shared_preferences_foundation","dependencies":[]},{"name":"shared_preferences_linux","dependencies":["path_provider_linux"]},{"name":"shared_preferences_web","dependencies":[]},{"name":"shared_preferences_windows","dependencies":["path_provider_windows"]}],"date_created":"2024-07-08 12:46:55.399944","version":"3.22.2"} \ No newline at end of file diff --git a/data/lib/api/ball_score/ball_score_model.dart b/data/lib/api/ball_score/ball_score_model.dart index f355db5d..fd83912c 100644 --- a/data/lib/api/ball_score/ball_score_model.dart +++ b/data/lib/api/ball_score/ball_score_model.dart @@ -1,5 +1,6 @@ // ignore_for_file: non_constant_identifier_names +import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:data/api/user/user_models.dart'; import 'package:data/extensions/double_extensions.dart'; import 'package:data/extensions/int_extensions.dart'; @@ -32,6 +33,11 @@ class BallScoreModel with _$BallScoreModel { factory BallScoreModel.fromJson(Map json) => _$BallScoreModelFromJson(json); + + factory BallScoreModel.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options) => + BallScoreModel.fromJson(snapshot.data()!); } @JsonEnum(valueField: "value") diff --git a/data/lib/api/innings/inning_model.dart b/data/lib/api/innings/inning_model.dart index 707639be..a08d0855 100644 --- a/data/lib/api/innings/inning_model.dart +++ b/data/lib/api/innings/inning_model.dart @@ -1,5 +1,6 @@ // ignore_for_file: non_constant_identifier_names +import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'inning_model.freezed.dart'; @@ -20,6 +21,11 @@ class InningModel with _$InningModel { factory InningModel.fromJson(Map json) => _$InningModelFromJson(json); + + factory InningModel.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options) => + InningModel.fromJson(snapshot.data()!); } @JsonEnum(valueField: "value") diff --git a/data/lib/api/match/match_model.dart b/data/lib/api/match/match_model.dart index e1d9394e..1fb85980 100644 --- a/data/lib/api/match/match_model.dart +++ b/data/lib/api/match/match_model.dart @@ -1,5 +1,6 @@ // ignore_for_file: non_constant_identifier_names +import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:data/api/team/team_model.dart'; import 'package:data/api/user/user_models.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -137,6 +138,8 @@ class MatchPlayer with _$MatchPlayer { @freezed class AddEditMatchRequest with _$AddEditMatchRequest { + // ignore: invalid_annotation_target + @JsonSerializable(anyMap: true, explicitToJson: true) const factory AddEditMatchRequest({ String? id, required List teams, @@ -167,10 +170,17 @@ class AddEditMatchRequest with _$AddEditMatchRequest { factory AddEditMatchRequest.fromJson(Map json) => _$AddEditMatchRequestFromJson(json); + + factory AddEditMatchRequest.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options) => + AddEditMatchRequest.fromJson(snapshot.data()!); } @freezed class AddMatchTeamRequest with _$AddMatchTeamRequest { + // ignore: invalid_annotation_target + @JsonSerializable(anyMap: true, explicitToJson: true) const factory AddMatchTeamRequest({ required String team_id, String? captain_id, @@ -187,6 +197,8 @@ class AddMatchTeamRequest with _$AddMatchTeamRequest { @freezed class MatchPlayerRequest with _$MatchPlayerRequest { + // ignore: invalid_annotation_target + @JsonSerializable(anyMap: true, explicitToJson: true) const factory MatchPlayerRequest({ required String id, required PlayerStatus status, diff --git a/data/lib/api/match/match_model.freezed.dart b/data/lib/api/match/match_model.freezed.dart index 02f753e0..e22c931a 100644 --- a/data/lib/api/match/match_model.freezed.dart +++ b/data/lib/api/match/match_model.freezed.dart @@ -1647,7 +1647,8 @@ class __$$AddEditMatchRequestImplCopyWithImpl<$Res> } /// @nodoc -@JsonSerializable() + +@JsonSerializable(anyMap: true, explicitToJson: true) class _$AddEditMatchRequestImpl implements _AddEditMatchRequest { const _$AddEditMatchRequestImpl( {this.id, @@ -2170,7 +2171,8 @@ class __$$AddMatchTeamRequestImplCopyWithImpl<$Res> } /// @nodoc -@JsonSerializable() + +@JsonSerializable(anyMap: true, explicitToJson: true) class _$AddMatchTeamRequestImpl implements _AddMatchTeamRequest { const _$AddMatchTeamRequestImpl( {required this.team_id, @@ -2386,7 +2388,8 @@ class __$$MatchPlayerRequestImplCopyWithImpl<$Res> } /// @nodoc -@JsonSerializable() + +@JsonSerializable(anyMap: true, explicitToJson: true) class _$MatchPlayerRequestImpl implements _MatchPlayerRequest { const _$MatchPlayerRequestImpl( {required this.id, required this.status, this.index}); diff --git a/data/lib/api/match/match_model.g.dart b/data/lib/api/match/match_model.g.dart index 717b9432..ce688372 100644 --- a/data/lib/api/match/match_model.g.dart +++ b/data/lib/api/match/match_model.g.dart @@ -177,12 +177,12 @@ const _$PlayerStatusEnumMap = { PlayerStatus.withdrawn: 7, }; -_$AddEditMatchRequestImpl _$$AddEditMatchRequestImplFromJson( - Map json) => +_$AddEditMatchRequestImpl _$$AddEditMatchRequestImplFromJson(Map json) => _$AddEditMatchRequestImpl( id: json['id'] as String?, teams: (json['teams'] as List) - .map((e) => AddMatchTeamRequest.fromJson(e as Map)) + .map((e) => + AddMatchTeamRequest.fromJson(Map.from(e as Map))) .toList(), match_type: $enumDecode(_$MatchTypeEnumMap, json['match_type']), number_of_over: (json['number_of_over'] as num).toInt(), @@ -235,7 +235,7 @@ Map _$$AddEditMatchRequestImplToJson( _$AddEditMatchRequestImpl instance) => { 'id': instance.id, - 'teams': instance.teams, + 'teams': instance.teams.map((e) => e.toJson()).toList(), 'match_type': _$MatchTypeEnumMap[instance.match_type]!, 'number_of_over': instance.number_of_over, 'players': instance.players, @@ -261,8 +261,7 @@ Map _$$AddEditMatchRequestImplToJson( 'current_playing_team_id': instance.current_playing_team_id, }; -_$AddMatchTeamRequestImpl _$$AddMatchTeamRequestImplFromJson( - Map json) => +_$AddMatchTeamRequestImpl _$$AddMatchTeamRequestImplFromJson(Map json) => _$AddMatchTeamRequestImpl( team_id: json['team_id'] as String, captain_id: json['captain_id'] as String?, @@ -271,8 +270,8 @@ _$AddMatchTeamRequestImpl _$$AddMatchTeamRequestImplFromJson( run: (json['run'] as num?)?.toInt() ?? 0, wicket: (json['wicket'] as num?)?.toInt() ?? 0, squad: (json['squad'] as List?) - ?.map( - (e) => MatchPlayerRequest.fromJson(e as Map)) + ?.map((e) => MatchPlayerRequest.fromJson( + Map.from(e as Map))) .toList() ?? const [], ); @@ -286,11 +285,10 @@ Map _$$AddMatchTeamRequestImplToJson( 'over': instance.over, 'run': instance.run, 'wicket': instance.wicket, - 'squad': instance.squad, + 'squad': instance.squad.map((e) => e.toJson()).toList(), }; -_$MatchPlayerRequestImpl _$$MatchPlayerRequestImplFromJson( - Map json) => +_$MatchPlayerRequestImpl _$$MatchPlayerRequestImplFromJson(Map json) => _$MatchPlayerRequestImpl( id: json['id'] as String, status: $enumDecode(_$PlayerStatusEnumMap, json['status']), diff --git a/data/lib/api/support/support_models.dart b/data/lib/api/support/support_models.dart index 33ab8c1b..e7f5acfe 100644 --- a/data/lib/api/support/support_models.dart +++ b/data/lib/api/support/support_models.dart @@ -1,3 +1,4 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'support_models.freezed.dart'; @@ -17,6 +18,11 @@ class AddSupportCaseRequest with _$AddSupportCaseRequest { factory AddSupportCaseRequest.fromJson(Map json) => _$AddSupportCaseRequestFromJson(json); + + factory AddSupportCaseRequest.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options) => + AddSupportCaseRequest.fromJson(snapshot.data()!); } enum AttachmentUploadStatus { diff --git a/data/lib/api/team/team_model.dart b/data/lib/api/team/team_model.dart index b0582ee1..26a45352 100644 --- a/data/lib/api/team/team_model.dart +++ b/data/lib/api/team/team_model.dart @@ -1,5 +1,6 @@ // ignore_for_file: non_constant_identifier_names +import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:data/api/user/user_models.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -39,4 +40,9 @@ class AddTeamRequestModel with _$AddTeamRequestModel { factory AddTeamRequestModel.fromJson(Map json) => _$AddTeamRequestModelFromJson(json); + + factory AddTeamRequestModel.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options) => + AddTeamRequestModel.fromJson(snapshot.data()!); } diff --git a/data/lib/api/user/user_models.dart b/data/lib/api/user/user_models.dart index d917ed62..c52c9eae 100644 --- a/data/lib/api/user/user_models.dart +++ b/data/lib/api/user/user_models.dart @@ -2,6 +2,7 @@ import 'dart:convert'; +import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'user_models.freezed.dart'; @@ -32,6 +33,11 @@ class UserModel with _$UserModel { factory UserModel.fromJson(Map json) => _$UserModelFromJson(json); + factory UserModel.fromFireStore( + DocumentSnapshot> snapshot, + SnapshotOptions? options) => + UserModel.fromJson(snapshot.data()!); + String toJsonString() => jsonEncode(toJson()); String get nameInitial => name?[0].toUpperCase() ?? '?'; diff --git a/data/lib/errors/app_error.dart b/data/lib/errors/app_error.dart index 6b2731a7..c60afd9d 100644 --- a/data/lib/errors/app_error.dart +++ b/data/lib/errors/app_error.dart @@ -31,7 +31,7 @@ class AppError implements Exception { } else if (error is FirebaseException) { return _handleFirebaseError(error); } else if (error is TypeError) { - return SomethingWentWrongError(stackTrace: error.stackTrace); + return SomethingWentWrongError(message: error.toString(), stackTrace: error.stackTrace); } else if (error is LargeAttachmentUploadError) { return const LargeAttachmentUploadError(); } else { diff --git a/data/lib/service/ball_score/ball_score_service.dart b/data/lib/service/ball_score/ball_score_service.dart index c8c7cbbf..5b9ed242 100644 --- a/data/lib/service/ball_score/ball_score_service.dart +++ b/data/lib/service/ball_score/ball_score_service.dart @@ -27,9 +27,15 @@ class BallScoreService { final MatchService _matchService; final InningsService _inningsService; String? _currentUserId; + final CollectionReference _ballScoreCollection; BallScoreService(this._firestore, this._matchService, this._inningsService, - this._currentUserId); + this._currentUserId) + : _ballScoreCollection = _firestore + .collection(FireStoreConst.ballScoresCollection) + .withConverter( + fromFirestore: BallScoreModel.fromFireStore, + toFirestore: (BallScoreModel score, _) => score.toJson()); Future addBallScoreAndUpdateTeamDetails({ required BallScoreModel score, @@ -44,8 +50,7 @@ class BallScoreService { MatchPlayerRequest? updatedPlayer, }) async { try { - DocumentReference scoreRef = - _firestore.collection(FireStoreConst.ballScoresCollection).doc(); + final scoreRef = _ballScoreCollection.doc(); await _firestore.runTransaction(maxAttempts: 1, (transaction) async { final overCount = double.parse("${score.over_number - 1}.${score.ball_number}"); @@ -72,7 +77,7 @@ class BallScoreService { // add ball transaction.set( scoreRef, - score.copyWith(id: scoreRef.id).toJson(), + score.copyWith(id: scoreRef.id), SetOptions(merge: true), ); }).catchError((error, stack) { @@ -85,68 +90,29 @@ class BallScoreService { Stream> getBallScoresStreamByInningIds( List inningIds) { - StreamController> controller = - StreamController>(); - - _firestore - .collection(FireStoreConst.ballScoresCollection) + return _ballScoreCollection .where(FireStoreConst.inningId, whereIn: inningIds) .snapshots() - .listen((QuerySnapshot> snapshot) { - try { - List changes = []; - for (var doc in snapshot.docChanges) { - final data = doc.doc.data(); - if (data != null) { - changes - .add(BallScoreChange(doc.type, BallScoreModel.fromJson(data))); - } - } - controller.add(changes); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - }); - - return controller.stream; + .map((event) => event.docChanges + .map((score) => BallScoreChange(score.type, score.doc.data()!)) + .toList()) + .handleError((error, stack) => throw AppError.fromError(error, stack)); } Stream> getCurrentUserRelatedBalls() { if (_currentUserId == null) { return Stream.value([]); } - StreamController> controller = - StreamController>(); - _firestore - .collection(FireStoreConst.ballScoresCollection) + + return _ballScoreCollection .where(Filter.or( Filter(FireStoreConst.bowlerId, isEqualTo: _currentUserId), Filter(FireStoreConst.batsmanId, isEqualTo: _currentUserId), Filter(FireStoreConst.wicketTakerId, isEqualTo: _currentUserId), Filter(FireStoreConst.playerOutId, isEqualTo: _currentUserId))) .snapshots() - .listen((snapshot) { - try { - final ballList = snapshot.docs.map((doc) { - final data = doc.data(); - return BallScoreModel.fromJson(data).copyWith(id: doc.id); - }).toList(); - - controller.add(ballList); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - }); - - return controller.stream; + .map((event) => event.docs.map((score) => score.data()).toList()) + .handleError((error, stack) => throw AppError.fromError(error, stack)); } Future deleteBallAndUpdateTeamDetails({ @@ -185,9 +151,7 @@ class BallScoreService { runs: totalBowlingTeamRuns); // delete ball - final docRef = _firestore - .collection(FireStoreConst.ballScoresCollection) - .doc(ballId); + final docRef = _ballScoreCollection.doc(ballId); transaction.delete(docRef); }); } catch (error, stack) { diff --git a/data/lib/service/innings/inning_service.dart b/data/lib/service/innings/inning_service.dart index bd5eae48..024a52c8 100644 --- a/data/lib/service/innings/inning_service.dart +++ b/data/lib/service/innings/inning_service.dart @@ -14,29 +14,14 @@ final inningServiceProvider = Provider((ref) { class InningsService { final FirebaseFirestore _firestore; + final CollectionReference _inningCollection; - InningsService(this._firestore); - - Future updateInning(InningModel inning) async { - try { - DocumentReference inningRef = _firestore - .collection(FireStoreConst.inningsCollection) - .doc(inning.id); - WriteBatch batch = _firestore.batch(); - - batch.set(inningRef, inning.toJson(), SetOptions(merge: true)); - String newInningId = inningRef.id; - - if (inning.id == null) { - batch.update(inningRef, {FireStoreConst.id: newInningId}); - } - - await batch.commit(); - return newInningId; - } catch (error, stack) { - throw AppError.fromError(error, stack); - } - } + InningsService(this._firestore) + : _inningCollection = _firestore + .collection(FireStoreConst.inningsCollection) + .withConverter( + fromFirestore: InningModel.fromFireStore, + toFirestore: (InningModel inning, _) => inning.toJson()); Future createInnings({ required String matchId, @@ -47,13 +32,11 @@ class InningsService { }) async { try { WriteBatch batch = _firestore.batch(); - - DocumentReference firstInningRef = - _firestore.collection(FireStoreConst.inningsCollection).doc(); - DocumentReference secondInningRef = - _firestore.collection(FireStoreConst.inningsCollection).doc(); + final firstInningRef = _inningCollection.doc(); + final secondInningRef = _inningCollection.doc(); final firstInning = InningModel( + id: firstInningRef.id, match_id: matchId, team_id: teamId, innings_status: firstInningStatus, @@ -63,6 +46,7 @@ class InningsService { ); final secondInning = InningModel( + id: secondInningRef.id, match_id: matchId, team_id: opponentTeamId, innings_status: secondInningStatus, @@ -71,48 +55,10 @@ class InningsService { total_wickets: 0, ); - // Set data for both innings using their respective references - batch.set( - firstInningRef, - firstInning.copyWith(id: firstInningRef.id).toJson(), - SetOptions(merge: true)); - batch.set( - secondInningRef, - secondInning.copyWith(id: secondInningRef.id).toJson(), - SetOptions(merge: true)); - - // Commit the batch - await batch.commit(); - } catch (error, stack) { - throw AppError.fromError(error, stack); - } - } - - Future getInningById(String id) async { - try { - DocumentReference inningRef = - _firestore.collection(FireStoreConst.inningsCollection).doc(id); - DocumentSnapshot snapshot = await inningRef.get(); - Map inningData = snapshot.data() as Map; - var inningModel = InningModel.fromJson(inningData); - return inningModel; - } catch (error, stack) { - throw AppError.fromError(error, stack); - } - } + batch.set(firstInningRef, firstInning, SetOptions(merge: true)); + batch.set(secondInningRef, secondInning , SetOptions(merge: true)); - Future> getInningsByMatchId( - {required String matchId}) async { - try { - final QuerySnapshot> snapshot = await _firestore - .collection(FireStoreConst.inningsCollection) - .where(FireStoreConst.matchId, isEqualTo: matchId) - .get(); - - return snapshot.docs.map((doc) { - final data = doc.data(); - return InningModel.fromJson(data).copyWith(id: doc.id); - }).toList(); + await batch.commit(); } catch (error, stack) { throw AppError.fromError(error, stack); } @@ -121,67 +67,11 @@ class InningsService { Stream> getInningsStreamByMatchId({ required String matchId, }) { - StreamController> controller = - StreamController>(); - - _firestore - .collection(FireStoreConst.inningsCollection) + return _inningCollection .where(FireStoreConst.matchId, isEqualTo: matchId) .snapshots() - .listen((QuerySnapshot> snapshot) { - try { - List innings = snapshot.docs.map((doc) { - final data = doc.data(); - return InningModel.fromJson(data).copyWith(id: doc.id); - }).toList(); - controller.add(innings); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - }); - - return controller.stream; - } - - Future updateInningScoreDetail({ - required String battingTeamInningId, - required double over, - required int totalRun, - required String bowlingTeamInningId, - required int wicketCount, - int? runs, - }) async { - try { - DocumentReference batInningRef = _firestore - .collection(FireStoreConst.inningsCollection) - .doc(battingTeamInningId); - - DocumentReference bowlInningRef = _firestore - .collection(FireStoreConst.inningsCollection) - .doc(bowlingTeamInningId); - WriteBatch batch = _firestore.batch(); - - batch.update(batInningRef, { - FireStoreConst.overs: over, - FireStoreConst.totalRuns: totalRun, - }); - if (runs != null) { - batch.update(bowlInningRef, { - FireStoreConst.totalWickets: wicketCount, - FireStoreConst.totalRuns: runs - }); - } else { - batch.update(bowlInningRef, {FireStoreConst.totalWickets: wicketCount}); - } - - await batch.commit(); - } catch (error, stack) { - throw AppError.fromError(error, stack); - } + .map((event) => event.docs.map((inning) => inning.data()).toList()) + .handleError((error, stack) => throw AppError.fromError(error, stack)); } void updateInningScoreDetailViaTransaction( @@ -194,13 +84,11 @@ class InningsService { int? runs, }) { try { - DocumentReference batInningRef = _firestore - .collection(FireStoreConst.inningsCollection) - .doc(battingTeamInningId); + final batInningRef = + _inningCollection.doc(battingTeamInningId); - DocumentReference bowlInningRef = _firestore - .collection(FireStoreConst.inningsCollection) - .doc(bowlingTeamInningId); + final bowlInningRef = + _inningCollection.doc(bowlingTeamInningId); Map battingUpdates = { FireStoreConst.totalRuns: totalRun, @@ -225,8 +113,7 @@ class InningsService { required InningStatus status, }) async { try { - DocumentReference batInningRef = - _firestore.collection(FireStoreConst.inningsCollection).doc(inningId); + final batInningRef = _inningCollection.doc(inningId); await batInningRef.update({FireStoreConst.inningsStatus: status.value}); } catch (error, stack) { throw AppError.fromError(error, stack); diff --git a/data/lib/service/match/match_service.dart b/data/lib/service/match/match_service.dart index 1bd70a56..70c3f802 100644 --- a/data/lib/service/match/match_service.dart +++ b/data/lib/service/match/match_service.dart @@ -4,6 +4,7 @@ import 'package:data/api/match/match_model.dart'; import 'package:data/api/team/team_model.dart'; import 'package:data/api/user/user_models.dart'; import 'package:data/errors/app_error.dart'; +import 'package:data/extensions/list_extensions.dart'; import 'package:data/service/team/team_service.dart'; import 'package:data/service/user/user_service.dart'; import 'package:data/utils/constant/firestore_constant.dart'; @@ -28,145 +29,108 @@ class MatchService { final TeamService _teamService; final UserService _userService; String? _currentUserId; + final CollectionReference _matchCollection; MatchService( this._firestore, this._teamService, this._userService, this._currentUserId, - ); + ) : _matchCollection = _firestore + .collection(FireStoreConst.matchesCollection) + .withConverter( + fromFirestore: AddEditMatchRequest.fromFireStore, + toFirestore: (AddEditMatchRequest match, _) => match.toJson()); Stream> getCurrentUserPlayedMatches() { if (_currentUserId == null) { return Stream.value([]); } - StreamController> controller = - StreamController>(); - - _firestore - .collection(FireStoreConst.matchesCollection) - .where( - Filter.and( - Filter(FireStoreConst.matchStatus, - isEqualTo: MatchStatus.finish.value), - Filter(FireStoreConst.players, arrayContains: _currentUserId), - ), - ) - .snapshots() - .listen((QuerySnapshot> snapshot) async { - try { - List matches = []; - matches = await Future.wait(snapshot.docs.map((mainDoc) async { - Map mainDocData = mainDoc.data(); - AddEditMatchRequest match = AddEditMatchRequest.fromJson(mainDocData); - List teams = await getTeamsList(match.teams); - return MatchModel( - id: match.id, - teams: teams, - match_type: match.match_type, - number_of_over: match.number_of_over, - over_per_bowler: match.over_per_bowler, - players: match.players, - team_ids: match.team_ids, - team_creator_ids: match.team_creator_ids, - city: match.city, - ground: match.ground, - start_time: match.start_time, - created_by: match.created_by, - ball_type: match.ball_type, - pitch_type: match.pitch_type, - match_status: match.match_status, - toss_winner_id: match.toss_winner_id, - toss_decision: match.toss_decision, - current_playing_team_id: match.current_playing_team_id, - ); - }).toList()); - controller.add(matches); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - }); + final filter = Filter.and( + Filter(FireStoreConst.matchStatus, isEqualTo: MatchStatus.finish.value), + Filter(FireStoreConst.players, arrayContains: _currentUserId), + ); - return controller.stream; + return _matchCollection + .where(filter) + .snapshots() + .asyncMap((snapshot) async { + return await Future.wait(snapshot.docs.map((mainDoc) async { + final match = mainDoc.data(); + List teams = await getTeamsList(match.teams); + return MatchModel( + id: match.id, + teams: teams, + match_type: match.match_type, + number_of_over: match.number_of_over, + over_per_bowler: match.over_per_bowler, + players: match.players, + team_ids: match.team_ids, + team_creator_ids: match.team_creator_ids, + city: match.city, + ground: match.ground, + start_time: match.start_time, + created_by: match.created_by, + ball_type: match.ball_type, + pitch_type: match.pitch_type, + match_status: match.match_status, + toss_winner_id: match.toss_winner_id, + toss_decision: match.toss_decision, + current_playing_team_id: match.current_playing_team_id, + ); + }).toList()); + }).handleError((error, stack) => throw AppError.fromError(error, stack)); } Stream> getCurrentUserRelatedMatches() { if (_currentUserId == null) { return Stream.value([]); } - StreamController> controller = - StreamController>(); - _firestore - .collection(FireStoreConst.matchesCollection) - .where(Filter.or( - Filter(FireStoreConst.createdBy, isEqualTo: _currentUserId), - Filter(FireStoreConst.players, arrayContains: _currentUserId), - Filter(FireStoreConst.teamCreatorIds, arrayContains: _currentUserId), - )) - .snapshots() - .listen((QuerySnapshot> snapshot) async { - try { - List matches = []; - matches = await Future.wait(snapshot.docs.map((mainDoc) async { - Map mainDocData = mainDoc.data(); - AddEditMatchRequest match = AddEditMatchRequest.fromJson(mainDocData); - List teams = await getTeamsList(match.teams); - return MatchModel( - id: match.id, - teams: teams, - match_type: match.match_type, - number_of_over: match.number_of_over, - over_per_bowler: match.over_per_bowler, - city: match.city, - players: match.players, - team_ids: match.team_ids, - team_creator_ids: match.team_creator_ids, - ground: match.ground, - start_time: match.start_time, - created_by: match.created_by, - ball_type: match.ball_type, - pitch_type: match.pitch_type, - match_status: match.match_status, - toss_winner_id: match.toss_winner_id, - toss_decision: match.toss_decision, - current_playing_team_id: match.current_playing_team_id, - ); - }).toList()); - controller.add(matches); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - }); + final filter = Filter.or( + Filter(FireStoreConst.createdBy, isEqualTo: _currentUserId), + Filter(FireStoreConst.players, arrayContains: _currentUserId), + Filter(FireStoreConst.teamCreatorIds, arrayContains: _currentUserId)); - return controller.stream; + return _matchCollection + .where(filter) + .snapshots() + .asyncMap((snapshot) async { + return await Future.wait(snapshot.docs.map((mainDoc) async { + final match = mainDoc.data(); + List teams = await getTeamsList(match.teams); + return MatchModel( + id: match.id, + teams: teams, + match_type: match.match_type, + number_of_over: match.number_of_over, + over_per_bowler: match.over_per_bowler, + city: match.city, + players: match.players, + team_ids: match.team_ids, + team_creator_ids: match.team_creator_ids, + ground: match.ground, + start_time: match.start_time, + created_by: match.created_by, + ball_type: match.ball_type, + pitch_type: match.pitch_type, + match_status: match.match_status, + toss_winner_id: match.toss_winner_id, + toss_decision: match.toss_decision, + current_playing_team_id: match.current_playing_team_id, + ); + }).toList()); + }).handleError((error, stack) => throw AppError.fromError(error, stack)); } - Future> getMatchesByTeamId(String teamId) async { - try { - CollectionReference matchCollection = - _firestore.collection(FireStoreConst.matchesCollection); - - QuerySnapshot mainCollectionSnapshot = await matchCollection - .where(FireStoreConst.teamIds, arrayContains: teamId) - .get(); - - List matches = []; - - matches = - await Future.wait(mainCollectionSnapshot.docs.map((mainDoc) async { - Map mainDocData = - mainDoc.data() as Map; - AddEditMatchRequest match = AddEditMatchRequest.fromJson(mainDocData); + Stream> getMatchesByTeamId(String teamId) { + return _matchCollection + .where(FireStoreConst.teamIds, arrayContains: teamId) + .snapshots() + .asyncMap((snapshot) async { + return await Future.wait(snapshot.docs.map((mainDoc) async { + final match = mainDoc.data(); List teams = await getTeamsList(match.teams); return MatchModel( @@ -175,10 +139,10 @@ class MatchService { match_type: match.match_type, number_of_over: match.number_of_over, over_per_bowler: match.over_per_bowler, + city: match.city, players: match.players, team_ids: match.team_ids, team_creator_ids: match.team_creator_ids, - city: match.city, ground: match.ground, start_time: match.start_time, created_by: match.created_by, @@ -190,94 +154,21 @@ class MatchService { current_playing_team_id: match.current_playing_team_id, ); }).toList()); - return matches; - } catch (error, stack) { - throw AppError.fromError(error, stack); - } + }).handleError((error, stack) => throw AppError.fromError(error, stack)); } Stream> getRunningMatches() { - StreamController> controller = - StreamController>(); - - _firestore - .collection(FireStoreConst.matchesCollection) + return _matchCollection .where(FireStoreConst.matchStatus, isEqualTo: MatchStatus.running.value) .snapshots() - .listen((QuerySnapshot> snapshot) async { + .asyncMap((snapshot) async { List matches = []; - try { - for (QueryDocumentSnapshot mainDoc in snapshot.docs) { - Map mainDocData = - mainDoc.data() as Map; - if (mainDocData[FireStoreConst.matchStatus] == - MatchStatus.running.value) { - AddEditMatchRequest match = - AddEditMatchRequest.fromJson(mainDocData); - - List teams = await getTeamsList(match.teams); - matches.add(MatchModel( - id: match.id, - teams: teams, - match_type: match.match_type, - number_of_over: match.number_of_over, - over_per_bowler: match.over_per_bowler, - players: match.players, - team_ids: match.team_ids, - team_creator_ids: match.team_creator_ids, - city: match.city, - ground: match.ground, - start_time: match.start_time, - created_by: match.created_by, - ball_type: match.ball_type, - pitch_type: match.pitch_type, - match_status: match.match_status, - toss_winner_id: match.toss_winner_id, - toss_decision: match.toss_decision, - current_playing_team_id: match.current_playing_team_id, - )); - } - } - controller.add(matches); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - }); - - return controller.stream; - } - - Stream getMatchStreamById(String id) { - StreamController controller = StreamController(); - StreamSubscription>>? subscription; - subscription = _firestore - .collection(FireStoreConst.matchesCollection) - .doc(id) - .snapshots() - .listen((DocumentSnapshot> snapshot) async { - if (snapshot.exists) { - try { - AddEditMatchRequest match = AddEditMatchRequest.fromJson( - snapshot.data() as Map); + for (final mainDoc in snapshot.docs) { + if (mainDoc.data().match_status == MatchStatus.running) { + final match = mainDoc.data(); List teams = await getTeamsList(match.teams); - List? umpires = - await getUserListFromUserIds(match.umpire_ids); - List? commentators = - await getUserListFromUserIds(match.commentator_ids); - List? scorers = - await getUserListFromUserIds(match.scorer_ids); - - UserModel? referee; - if (match.referee_id != null) { - referee = await _userService.getUserById(match.referee_id!); - } - - var matchModel = MatchModel( + matches.add(MatchModel( id: match.id, teams: teams, match_type: match.match_type, @@ -293,45 +184,94 @@ class MatchService { ball_type: match.ball_type, pitch_type: match.pitch_type, match_status: match.match_status, - commentators: commentators, - referee: referee, - scorers: scorers, - umpires: umpires, - power_play_overs1: match.power_play_overs1 ?? [], - power_play_overs2: match.power_play_overs2 ?? [], - power_play_overs3: match.power_play_overs3 ?? [], - toss_decision: match.toss_decision, toss_winner_id: match.toss_winner_id, + toss_decision: match.toss_decision, current_playing_team_id: match.current_playing_team_id, - ); - - controller.add(matchModel); - } catch (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - subscription?.cancel(); + )); } - } else { - controller.close(); - subscription?.cancel(); } - }, onError: (error, stack) { - controller.addError(AppError.fromError(error, stack)); - controller.close(); - subscription?.cancel(); - }); + return matches; + }).handleError((error, stack) => throw AppError.fromError(error, stack)); + } + + Stream getMatchStreamById(String id) { + return _matchCollection.doc(id).snapshots().asyncMap((snapshot) async { + final match = snapshot.data(); + if (match == null) { + return MatchModel( + teams: [], + match_type: MatchType.limitedOvers, + number_of_over: 0, + over_per_bowler: 0, + city: '', + ground: '', + start_time: DateTime.now(), + ball_type: BallType.leather, + pitch_type: PitchType.turf, + created_by: '', + match_status: MatchStatus.running); + } + + List teams = await getTeamsList(match.teams); + List? umpires = await getUserListFromUserIds(match.umpire_ids); + List? commentators = + await getUserListFromUserIds(match.commentator_ids); + List? scorers = await getUserListFromUserIds(match.scorer_ids); + + UserModel? referee; + if (match.referee_id != null) { + referee = await _userService.getUserById(match.referee_id!); + } - return controller.stream; + return MatchModel( + id: match.id, + teams: teams, + match_type: match.match_type, + number_of_over: match.number_of_over, + over_per_bowler: match.over_per_bowler, + players: match.players, + team_ids: match.team_ids, + team_creator_ids: match.team_creator_ids, + city: match.city, + ground: match.ground, + start_time: match.start_time, + created_by: match.created_by, + ball_type: match.ball_type, + pitch_type: match.pitch_type, + match_status: match.match_status, + commentators: commentators, + referee: referee, + scorers: scorers, + umpires: umpires, + power_play_overs1: match.power_play_overs1 ?? [], + power_play_overs2: match.power_play_overs2 ?? [], + power_play_overs3: match.power_play_overs3 ?? [], + toss_decision: match.toss_decision, + toss_winner_id: match.toss_winner_id, + current_playing_team_id: match.current_playing_team_id, + ); + }).handleError((error, stack) => throw AppError.fromError(error, stack)); } Future getMatchById(String id) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(id); - DocumentSnapshot snapshot = await matchRef.get(); + final snapshot = await _matchCollection.doc(id).get(); - AddEditMatchRequest match = - AddEditMatchRequest.fromJson(snapshot.data() as Map); + final match = snapshot.data(); + if (match == null) { + return MatchModel( + teams: [], + match_type: MatchType.limitedOvers, + number_of_over: 0, + over_per_bowler: 0, + city: '', + ground: '', + start_time: DateTime.now(), + ball_type: BallType.leather, + pitch_type: PitchType.turf, + created_by: '', + match_status: MatchStatus.running); + } List teams = await getTeamsList(match.teams); List? umpires = await getUserListFromUserIds(match.umpire_ids); @@ -380,34 +320,10 @@ class MatchService { Future updateMatch(AddEditMatchRequest match) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(match.id); - WriteBatch batch = _firestore.batch(); - - Map matchJson = match.toJson(); - - final teamsJson = (matchJson[FireStoreConst.teams] as List).map((team) { - final teamRequest = (team as AddMatchTeamRequest).toJson(); - final squadJson = (team) - .squad - .map((playerRequest) => playerRequest.toJson()) - .toList(); - teamRequest[FireStoreConst.squad] = squadJson; - - return teamRequest; - }).toList(); - - matchJson[FireStoreConst.teams] = teamsJson; - - batch.set(matchRef, matchJson, SetOptions(merge: true)); - String newMatchId = matchRef.id; - - if (match.id == null) { - batch.update(matchRef, {FireStoreConst.id: newMatchId}); - } - - await batch.commit(); - return newMatchId; + final matchRef = _matchCollection.doc(match.id); + await matchRef.set( + match.copyWith(id: matchRef.id), SetOptions(merge: true)); + return matchRef.id; } catch (error, stack) { throw AppError.fromError(error, stack); } @@ -416,8 +332,7 @@ class MatchService { Future updateTossDetails(String matchId, String tossWinnerId, TossDecision tossDecision, String currentPlayingTeam) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(matchId); + final matchRef = _matchCollection.doc(matchId); Map tossDetails = { FireStoreConst.tossWinnerId: tossWinnerId, @@ -433,8 +348,7 @@ class MatchService { Future updateMatchStatus(String matchId, MatchStatus status) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(matchId); + final matchRef = _matchCollection.doc(matchId); Map matchStatus = { FireStoreConst.matchStatus: status.value, @@ -446,47 +360,6 @@ class MatchService { } } - Future updateTeamScore({ - required String matchId, - required String battingTeamId, - required int totalRun, - required double over, - required String bowlingTeamId, - required int wicket, - int? runs, - }) async { - try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(matchId); - - await _firestore.runTransaction((transaction) async { - DocumentSnapshot snapshot = await transaction.get(matchRef); - - List> existingTeams = - List>.from( - snapshot.get(FireStoreConst.teams) ?? []); - - int battingTeamIndex = existingTeams - .indexWhere((team) => team[FireStoreConst.teamId] == battingTeamId); - int bowlingTeamIndex = existingTeams - .indexWhere((team) => team[FireStoreConst.teamId] == bowlingTeamId); - - if (battingTeamIndex != -1 && bowlingTeamIndex != -1) { - existingTeams[battingTeamIndex][FireStoreConst.run] = totalRun; - existingTeams[battingTeamIndex][FireStoreConst.over] = over; - existingTeams[bowlingTeamIndex][FireStoreConst.wicket] = wicket; - if (runs != null) { - existingTeams[bowlingTeamIndex][FireStoreConst.run] = runs; - } - } - - transaction.update(matchRef, {FireStoreConst.teams: existingTeams}); - }); - } catch (error, stack) { - throw AppError.fromError(error, stack); - } - } - Future updateTeamScoreAndSquadViaTransaction( Transaction transaction, { required String matchId, @@ -499,49 +372,48 @@ class MatchService { List? updatedMatchPlayer, }) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(matchId); + final matchRef = _matchCollection.doc(matchId); - DocumentSnapshot snapshot = await transaction.get(matchRef); + final snapshot = await transaction.get(matchRef); - List> existingTeams = - List>.from( - snapshot.get(FireStoreConst.teams) ?? []); + final existingTeams = snapshot.data()?.teams ?? []; - int battingTeamIndex = existingTeams - .indexWhere((team) => team[FireStoreConst.teamId] == battingTeamId); - int bowlingTeamIndex = existingTeams - .indexWhere((team) => team[FireStoreConst.teamId] == bowlingTeamId); + int battingTeamIndex = + existingTeams.indexWhere((team) => team.team_id == battingTeamId); + int bowlingTeamIndex = + existingTeams.indexWhere((team) => team.team_id == bowlingTeamId); + var battingTeam = existingTeams[battingTeamIndex]; + var bowlingTeam = existingTeams[bowlingTeamIndex]; if (battingTeamIndex != -1 && bowlingTeamIndex != -1) { if (updatedMatchPlayer != null) { - List> updatedSquad = - List>.from( - existingTeams[battingTeamIndex][FireStoreConst.squad] ?? []); + var updatedSquad = existingTeams[battingTeamIndex].squad.toList(); for (final matchPlayer in updatedMatchPlayer) { - int existingPlayerIndex = updatedSquad.indexWhere( - (player) => player[FireStoreConst.id] == matchPlayer.id); + int existingPlayerIndex = updatedSquad + .indexWhere((player) => player.id == matchPlayer.id); if (existingPlayerIndex != -1) { - updatedSquad[existingPlayerIndex] = matchPlayer.toJson(); + updatedSquad[existingPlayerIndex] = matchPlayer; } else { - updatedSquad.add(matchPlayer.toJson()); + updatedSquad.add(matchPlayer); } } - existingTeams[battingTeamIndex][FireStoreConst.squad] = updatedSquad; + battingTeam = battingTeam.copyWith(squad: updatedSquad); } - existingTeams[battingTeamIndex][FireStoreConst.run] = totalRun; + battingTeam = battingTeam.copyWith(run: totalRun); if (over != null) { - existingTeams[battingTeamIndex][FireStoreConst.over] = over; + battingTeam = battingTeam.copyWith(over: over); } - existingTeams[bowlingTeamIndex][FireStoreConst.wicket] = wicket; + bowlingTeam = bowlingTeam.copyWith(wicket: wicket); if (runs != null) { - existingTeams[bowlingTeamIndex][FireStoreConst.run] = runs; + bowlingTeam = bowlingTeam.copyWith(run: runs); } } - transaction.update(matchRef, {FireStoreConst.teams: existingTeams}); + transaction.update(matchRef, { + FireStoreConst.teams: [battingTeam.toJson(), bowlingTeam.toJson()] + }); } catch (error, stack) { throw AppError.fromError(error, stack); } @@ -550,8 +422,7 @@ class MatchService { Future updateCurrentPlayingTeam( {required String matchId, required String teamId}) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(matchId); + final matchRef = _matchCollection.doc(matchId); await matchRef.update({FireStoreConst.currentPlayingTeamId: teamId}); } catch (error, stack) { @@ -562,38 +433,38 @@ class MatchService { Future updateTeamsSquad( String matchId, AddMatchTeamRequest teamRequest) async { try { - DocumentReference matchRef = - _firestore.collection(FireStoreConst.matchesCollection).doc(matchId); + final matchRef = _matchCollection.doc(matchId); await _firestore.runTransaction((transaction) async { - DocumentSnapshot snapshot = await transaction.get(matchRef); - - List> existingTeams = - List>.from( - snapshot.get(FireStoreConst.teams) ?? []); + final snapshot = await transaction.get(matchRef); - int teamIndex = existingTeams.indexWhere( - (team) => team[FireStoreConst.teamId] == teamRequest.team_id); + final existingTeams = snapshot.data()?.teams ?? []; + var updatedTeams = existingTeams; + int teamIndex = existingTeams + .indexWhere((team) => team.team_id == teamRequest.team_id); if (teamIndex != -1) { - List> updatedSquad = - List>.from( - existingTeams[teamIndex][FireStoreConst.squad] ?? []); + var team = existingTeams[teamIndex]; + var updatedSquad = existingTeams[teamIndex].squad.toList(); for (var updatedPlayer in teamRequest.squad) { - int existingPlayerIndex = updatedSquad.indexWhere( - (player) => player[FireStoreConst.id] == updatedPlayer.id); + int existingPlayerIndex = updatedSquad + .indexWhere((player) => player.id == updatedPlayer.id); if (existingPlayerIndex != -1) { - updatedSquad[existingPlayerIndex] = updatedPlayer.toJson(); + updatedSquad[existingPlayerIndex] = updatedPlayer; } else { - updatedSquad.add(updatedPlayer.toJson()); + updatedSquad.add(updatedPlayer); } } - existingTeams[teamIndex][FireStoreConst.squad] = updatedSquad; + team = team.copyWith(squad: updatedSquad); + updatedTeams = updatedTeams.updateWhere( + where: (element) => element.team_id == team.team_id, + updated: (oldElement) => team); } - transaction.update(matchRef, {FireStoreConst.teams: existingTeams}); + transaction.update(matchRef, + {FireStoreConst.teams: updatedTeams.map((e) => e.toJson())}); }); } catch (error, stack) { throw AppError.fromError(error, stack); @@ -602,10 +473,7 @@ class MatchService { Future deleteMatch(String matchId) async { try { - await _firestore - .collection(FireStoreConst.matchesCollection) - .doc(matchId) - .delete(); + await _matchCollection.doc(matchId).delete(); } catch (error, stack) { throw AppError.fromError(error, stack); } diff --git a/data/lib/service/support/support_service.dart b/data/lib/service/support/support_service.dart index c04c3530..874d23b8 100644 --- a/data/lib/service/support/support_service.dart +++ b/data/lib/service/support/support_service.dart @@ -10,25 +10,23 @@ final supportServiceProvider = Provider( ); class SupportService { - final FirebaseFirestore _firestore; + final FirebaseFirestore firestore; + final CollectionReference _supportCollection; - SupportService(this._firestore); + SupportService(this.firestore) + : _supportCollection = firestore + .collection(FireStoreConst.supportCollection) + .withConverter( + fromFirestore: AddSupportCaseRequest.fromFireStore, + toFirestore: (AddSupportCaseRequest support, _) => + support.toJson()); Future addSupportCase(AddSupportCaseRequest supportCase) async { try { - DocumentReference supportCaseRef = _firestore - .collection(FireStoreConst.supportCollection) - .doc(supportCase.id); - WriteBatch batch = _firestore.batch(); - - batch.set(supportCaseRef, supportCase.toJson(), SetOptions(merge: true)); - String newSupportCaseId = supportCaseRef.id; - - if (supportCase.id == null) { - batch.update(supportCaseRef, {FireStoreConst.id: newSupportCaseId}); - } - await batch.commit(); - return newSupportCaseId; + final supportCaseRef = _supportCollection.doc(supportCase.id); + await supportCaseRef.set( + supportCase.copyWith(id: supportCaseRef.id), SetOptions(merge: true)); + return supportCaseRef.id; } catch (error, stack) { throw AppError.fromError(error, stack); } diff --git a/data/lib/service/team/team_service.dart b/data/lib/service/team/team_service.dart index 8e42bb38..28eebc4e 100644 --- a/data/lib/service/team/team_service.dart +++ b/data/lib/service/team/team_service.dart @@ -23,39 +23,28 @@ final teamServiceProvider = Provider((ref) { class TeamService { String? _currentUserId; - final FirebaseFirestore _firestore; - final UserService _userService; - - TeamService(this._currentUserId, this._firestore, this._userService); - Future updateTeam(AddTeamRequestModel team) async { - try { - DocumentReference teamRef = - _firestore.collection(FireStoreConst.teamsCollection).doc(team.id); - WriteBatch batch = _firestore.batch(); + final FirebaseFirestore firestore; + final UserService _userService; + final CollectionReference _teamsCollection; - batch.set(teamRef, team.toJson(), SetOptions(merge: true)); - String newTeamId = teamRef.id; - - if (team.id == null) { - batch.update(teamRef, {FireStoreConst.id: newTeamId}); - } - await batch.commit(); - return newTeamId; - } catch (error, stack) { - throw AppError.fromError(error, stack); - } - } + TeamService(this._currentUserId, this.firestore, this._userService) + : _teamsCollection = firestore + .collection(FireStoreConst.teamsCollection) + .withConverter( + fromFirestore: AddTeamRequestModel.fromFireStore, + toFirestore: (AddTeamRequestModel team, _) => team.toJson()); Future getTeamById(String teamId) async { try { - CollectionReference teamsCollection = - _firestore.collection(FireStoreConst.teamsCollection); + final teamDoc = await _teamsCollection.doc(teamId).get(); - DocumentSnapshot teamDoc = await teamsCollection.doc(teamId).get(); + final teamRequestModel = teamDoc.data(); - AddTeamRequestModel teamRequestModel = - AddTeamRequestModel.fromJson(teamDoc.data() as Map); + if (teamRequestModel == null) { + return TeamModel( + id: teamId, name: "Deleted Team", name_lowercase: "deletedteam"); + } final member = (teamRequestModel.players?.isNotEmpty ?? false) ? await getMemberListFromUserIds(teamRequestModel.players ?? []) @@ -77,25 +66,44 @@ class TeamService { } } + Stream getTeamStreamById(String teamId) { + return _teamsCollection.doc(teamId).snapshots().asyncMap((teamDoc) async { + final teamRequestModel = teamDoc.data(); + if (teamRequestModel == null) { + return TeamModel( + id: teamId, name: "Deleted Team", name_lowercase: "deletedteam"); + } + final member = (teamRequestModel.players?.isNotEmpty ?? false) + ? await getMemberListFromUserIds(teamRequestModel.players ?? []) + : null; + + final team = TeamModel( + name: teamRequestModel.name, + name_lowercase: teamRequestModel.name_lowercase, + id: teamRequestModel.id, + city: teamRequestModel.city, + created_at: teamRequestModel.created_at, + created_by: teamRequestModel.created_by, + profile_img_url: teamRequestModel.profile_img_url, + players: member); + return team; + }).handleError((error, stack) => AppError.fromError(error, stack)); + } + Stream> getUserRelatedTeams() { if (_currentUserId == null) { return Stream.value([]); } - - return _firestore - .collection(FireStoreConst.teamsCollection) - .where( - Filter.or( - Filter(FireStoreConst.createdBy, isEqualTo: _currentUserId), - Filter(FireStoreConst.players, arrayContains: _currentUserId), - ), - ) + final filter = Filter.or( + Filter(FireStoreConst.createdBy, isEqualTo: _currentUserId), + Filter(FireStoreConst.players, arrayContains: _currentUserId), + ); + return _teamsCollection + .where(filter) .snapshots() .asyncMap((snapshot) async { - List teams = []; - for (QueryDocumentSnapshot mainDoc in snapshot.docs) { - AddTeamRequestModel teamRequestModel = AddTeamRequestModel.fromJson( - mainDoc.data() as Map); + return await Future.wait(snapshot.docs.map((mainDoc) async { + AddTeamRequestModel teamRequestModel = mainDoc.data(); final member = (teamRequestModel.players?.isNotEmpty ?? false) ? await getMemberListFromUserIds(teamRequestModel.players ?? []) @@ -111,27 +119,18 @@ class TeamService { profile_img_url: teamRequestModel.profile_img_url, players: member, ); - - teams.add(team); - } - return teams; - }).handleError((error, stack) { - throw AppError.fromError(error, stack); - }); + return team; + })); + }).handleError((error, stack) => throw AppError.fromError(error, stack)); } - Future> getUserOwnedTeams() async { - try { - QuerySnapshot mainCollectionSnapshot = await _firestore - .collection(FireStoreConst.teamsCollection) - .where(FireStoreConst.createdBy, isEqualTo: _currentUserId) - .get(); - - List teams = []; - - for (QueryDocumentSnapshot mainDoc in mainCollectionSnapshot.docs) { - AddTeamRequestModel teamRequestModel = AddTeamRequestModel.fromJson( - mainDoc.data() as Map); + Stream> getUserOwnedTeams() { + return _teamsCollection + .where(FireStoreConst.createdBy, isEqualTo: _currentUserId) + .snapshots() + .asyncMap((snapshot) async { + return await Future.wait(snapshot.docs.map((mainDoc) async { + AddTeamRequestModel teamRequestModel = mainDoc.data(); final member = (teamRequestModel.players?.isNotEmpty ?? false) ? await getMemberListFromUserIds(teamRequestModel.players ?? []) @@ -146,35 +145,27 @@ class TeamService { created_by: teamRequestModel.created_by, profile_img_url: teamRequestModel.profile_img_url, players: member); - - teams.add(team); - } - - return teams; - } catch (error, stack) { - throw AppError.fromError(error, stack); - } + return team; + }).toList()); + }).handleError((error, stack) => throw AppError.fromError(error, stack)); } - Future updateProfileImageUrl(String teamId, String? imageUrl) async { + Future updateTeam(AddTeamRequestModel team) async { try { - DocumentReference teamRef = - _firestore.collection(FireStoreConst.teamsCollection).doc(teamId); - - await teamRef.set({ - FireStoreConst.profileImageUrl: imageUrl, - }, SetOptions(merge: true)); + final teamRef = _teamsCollection.doc(team.id); + await teamRef.set(team.copyWith(id: teamRef.id), SetOptions(merge: true)); + return teamRef.id; } catch (error, stack) { throw AppError.fromError(error, stack); } } - Future deleteTeam(String teamId) async { + Future updateProfileImageUrl(String teamId, String? imageUrl) async { try { - await _firestore - .collection(FireStoreConst.teamsCollection) - .doc(teamId) - .delete(); + final teamRef = _teamsCollection.doc(teamId); + await teamRef.update({ + FireStoreConst.profileImageUrl: imageUrl, + }); } catch (error, stack) { throw AppError.fromError(error, stack); } @@ -182,12 +173,9 @@ class TeamService { Future addPlayersToTeam(String teamId, List players) async { try { - DocumentReference teamRef = - _firestore.collection(FireStoreConst.teamsCollection).doc(teamId); - - await teamRef.set( - {FireStoreConst.players: FieldValue.arrayUnion(players)}, - SetOptions(merge: true)); + final teamRef = _teamsCollection.doc(teamId); + await teamRef + .update({FireStoreConst.players: FieldValue.arrayUnion(players)}); } catch (error, stack) { throw AppError.fromError(error, stack); } @@ -196,9 +184,7 @@ class TeamService { Future removePlayersFromTeam( String teamId, List playerIds) async { try { - DocumentReference teamRef = - _firestore.collection(FireStoreConst.teamsCollection).doc(teamId); - + final teamRef = _teamsCollection.doc(teamId); await teamRef .update({FireStoreConst.players: FieldValue.arrayRemove(playerIds)}); } catch (error, stack) { @@ -208,8 +194,7 @@ class TeamService { Future isTeamNameAvailable(String teamName) async { try { - QuerySnapshot teamSnap = await _firestore - .collection(FireStoreConst.teamsCollection) + QuerySnapshot teamSnap = await _teamsCollection .where(FireStoreConst.nameLowercase, isEqualTo: teamName.caseAndSpaceInsensitive) .get(); @@ -222,8 +207,7 @@ class TeamService { Future> searchTeam(String searchKey) async { try { - final QuerySnapshot> snapshot = await _firestore - .collection(FireStoreConst.teamsCollection) + final snapshot = await _teamsCollection .where(FireStoreConst.nameLowercase, isGreaterThanOrEqualTo: searchKey.caseAndSpaceInsensitive) .where(FireStoreConst.nameLowercase, @@ -232,9 +216,8 @@ class TeamService { List teams = []; - for (QueryDocumentSnapshot mainDoc in snapshot.docs) { - AddTeamRequestModel teamRequestModel = AddTeamRequestModel.fromJson( - mainDoc.data() as Map); + for (final mainDoc in snapshot.docs) { + AddTeamRequestModel teamRequestModel = mainDoc.data(); final member = (teamRequestModel.players?.isNotEmpty ?? false) ? await getMemberListFromUserIds(teamRequestModel.players ?? []) @@ -259,6 +242,14 @@ class TeamService { } } + Future deleteTeam(String teamId) async { + try { + await _teamsCollection.doc(teamId).delete(); + } catch (error, stack) { + throw AppError.fromError(error, stack); + } + } + // Helper Method Future> getMemberListFromUserIds(List users) async { try { diff --git a/data/lib/service/user/user_service.dart b/data/lib/service/user/user_service.dart index 549a3a94..6a75e138 100644 --- a/data/lib/service/user/user_service.dart +++ b/data/lib/service/user/user_service.dart @@ -18,19 +18,23 @@ final userServiceProvider = Provider((ref) { class UserService { UserModel? _currentUser; final StateController _currentUserJsonController; - final FirebaseFirestore _firestore; + + final FirebaseFirestore firestore; + final CollectionReference _userCollection; UserService( - this._currentUser, this._currentUserJsonController, this._firestore); + this._currentUser, this._currentUserJsonController, this.firestore) + : _userCollection = firestore + .collection(FireStoreConst.usersCollection) + .withConverter( + fromFirestore: UserModel.fromFireStore, + toFirestore: (UserModel user, _) => user.toJson()); Future getUser(String id) async { try { - DocumentReference userRef = - _firestore.collection(FireStoreConst.usersCollection).doc(id); - DocumentSnapshot snapshot = await userRef.get(); - Map userData = snapshot.data() as Map; - var userModel = UserModel.fromJson(userData); - _currentUserJsonController.state = userModel.toJsonString(); + final snapshot = await _userCollection.doc(id).get(); + var userModel = snapshot.data(); + _currentUserJsonController.state = userModel?.toJsonString(); } catch (error, stack) { throw AppError.fromError(error, stack); } @@ -38,10 +42,9 @@ class UserService { Future updateUser(UserModel user) async { try { - DocumentReference userRef = - _firestore.collection(FireStoreConst.usersCollection).doc(user.id); + final userRef = _userCollection.doc(user.id); - await userRef.set(user.toJson(), SetOptions(merge: true)); + await userRef.set(user, SetOptions(merge: true)); _currentUserJsonController.state = user.toJsonString(); } catch (error, stack) { @@ -51,10 +54,7 @@ class UserService { Future deleteUser() async { try { - await _firestore - .collection(FireStoreConst.usersCollection) - .doc(_currentUser?.id) - .delete(); + await _userCollection.doc(_currentUser?.id).delete(); _currentUserJsonController.state = null; } catch (error, stack) { throw AppError.fromError(error, stack); @@ -63,11 +63,15 @@ class UserService { Future getUserById(String id) async { try { - DocumentReference userRef = - _firestore.collection(FireStoreConst.usersCollection).doc(id); - DocumentSnapshot snapshot = await userRef.get(); - Map userData = snapshot.data() as Map; - var userModel = UserModel.fromJson(userData); + final snapshot = await _userCollection.doc(id).get(); + var userModel = snapshot.data(); + if (userModel == null) { + return UserModel( + id: id, + name: "Deactivated User", + created_at: DateTime(1950), + location: "--"); + } return userModel; } catch (error, stack) { throw AppError.fromError(error, stack); @@ -78,25 +82,21 @@ class UserService { List users = []; try { for (final tenIds in ids.chunked(10)) { - QuerySnapshot> snapshot = await _firestore - .collection(FireStoreConst.usersCollection) + final snapshot = await _userCollection .where(FireStoreConst.id, whereIn: tenIds) .get(); users.addAll(snapshot.docs.map((doc) { - final data = doc.data(); - return UserModel.fromJson(data).copyWith(id: doc.id); + return doc.data(); }).toList()); final deactivatedUserIds = tenIds.where((id) => !users.map((user) => user.id).contains(id)); - users.addAll(deactivatedUserIds.map( - (id) => UserModel( - id: id, - name: "Deactivated User", - created_at: DateTime(1950), - location: "--"), - )); + users.addAll(deactivatedUserIds.map((id) => UserModel( + id: id, + name: "Deactivated User", + created_at: DateTime(1950), + location: "--"))); } return users; @@ -107,8 +107,7 @@ class UserService { Future> searchUser(String searchKey) async { try { - final QuerySnapshot> snapshot = await _firestore - .collection(FireStoreConst.usersCollection) + final snapshot = await _userCollection .where(FireStoreConst.nameLowercase, isGreaterThanOrEqualTo: searchKey.toLowerCase()) .where(FireStoreConst.nameLowercase, @@ -116,8 +115,7 @@ class UserService { .get(); return snapshot.docs.map((doc) { - final data = doc.data(); - return UserModel.fromJson(data).copyWith(id: doc.id); + return doc.data(); }).toList(); } catch (error, stack) { throw AppError.fromError(error, stack); diff --git a/data/lib/utils/combine_latest.dart b/data/lib/utils/combine_latest.dart new file mode 100644 index 00000000..6c186d49 --- /dev/null +++ b/data/lib/utils/combine_latest.dart @@ -0,0 +1,8 @@ +import 'package:stream_transform/stream_transform.dart'; + +Stream<(T1, T2)> combineLatest2( + Stream stream1, + Stream stream2, +) { + return stream1.combineLatest(stream2, (t1, t2) => (t1, t2)); +} \ No newline at end of file diff --git a/data/pubspec.yaml b/data/pubspec.yaml index f1244a78..9f0c443d 100644 --- a/data/pubspec.yaml +++ b/data/pubspec.yaml @@ -23,14 +23,15 @@ dependencies: # io dio: ^5.0.2 - json_annotation: ^4.8.1 + json_annotation: ^4.9.0 json_serializable: ^6.7.1 freezed_annotation: ^2.4.1 + stream_transform: ^2.1.0 # device + package info device_info_plus: ^10.1.0 package_info_plus: ^8.0.0 - flutter_timezone: ^1.0.8 + flutter_timezone: ^2.0.0 path: ^1.8.3 # state management diff --git a/khelo/lib/ui/flow/home/home_screen.dart b/khelo/lib/ui/flow/home/home_screen.dart index 3c82fb7d..c19439de 100644 --- a/khelo/lib/ui/flow/home/home_screen.dart +++ b/khelo/lib/ui/flow/home/home_screen.dart @@ -73,7 +73,7 @@ class _HomeScreenState extends ConsumerState { return Column( children: [ SizedBox( - height: 176, + height: 165, child: state.matches.length == 1 ? Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), @@ -128,7 +128,7 @@ class _HomeScreenState extends ConsumerState { match.teams.first, match.teams.elementAt(1).wicket, ), - const SizedBox(height: 16), + const SizedBox(height: 22), _teamScore( context, match.teams.elementAt(1), @@ -157,8 +157,8 @@ class _HomeScreenState extends ConsumerState { Expanded( child: Text(matchTeam.team.name, overflow: TextOverflow.ellipsis, - maxLines: 2, - style: AppTextStyle.subtitle1 + maxLines: 1, + style: AppTextStyle.subtitle3 .copyWith(color: context.colorScheme.textPrimary)), ), if (matchTeam.over != 0) ...[ @@ -186,8 +186,8 @@ class _HomeScreenState extends ConsumerState { overflow: TextOverflow.ellipsis, TextSpan( text: match.start_time.format(context, DateFormatType.dateAndTime), - style: AppTextStyle.body2 - .copyWith(color: context.colorScheme.textPrimary), + style: AppTextStyle.caption + .copyWith(color: context.colorScheme.textSecondary), children: [ WidgetSpan( alignment: PlaceholderAlignment.middle, @@ -197,7 +197,7 @@ class _HomeScreenState extends ConsumerState { margin: const EdgeInsets.symmetric(horizontal: 8), decoration: BoxDecoration( shape: BoxShape.circle, - color: context.colorScheme.textPrimary, + color: context.colorScheme.textSecondary, ), )), TextSpan(text: match.ground) diff --git a/khelo/lib/ui/flow/matches/match_detail/components/match_detail_scorecard_view.dart b/khelo/lib/ui/flow/matches/match_detail/components/match_detail_scorecard_view.dart index 7bff5411..c1ab7695 100644 --- a/khelo/lib/ui/flow/matches/match_detail/components/match_detail_scorecard_view.dart +++ b/khelo/lib/ui/flow/matches/match_detail/components/match_detail_scorecard_view.dart @@ -553,6 +553,9 @@ class MatchDetailScorecardView extends ConsumerWidget { style: AppTextStyle.subtitle2 .copyWith(color: context.colorScheme.textPrimary), ))); + if (index != powerPlays.length) { + children.add(Divider(height: 0, color: context.colorScheme.outline)); + } } return Column( children: children, diff --git a/khelo/lib/ui/flow/matches/match_detail/match_detail_tab_view_model.dart b/khelo/lib/ui/flow/matches/match_detail/match_detail_tab_view_model.dart index c20b5dd2..1ed8c53d 100644 --- a/khelo/lib/ui/flow/matches/match_detail/match_detail_tab_view_model.dart +++ b/khelo/lib/ui/flow/matches/match_detail/match_detail_tab_view_model.dart @@ -8,6 +8,7 @@ import 'package:data/errors/app_error.dart'; import 'package:data/service/ball_score/ball_score_service.dart'; import 'package:data/service/innings/inning_service.dart'; import 'package:data/service/match/match_service.dart'; +import 'package:data/utils/combine_latest.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -19,7 +20,6 @@ import 'package:khelo/ui/flow/matches/match_detail/components/match_detail_info_ import 'package:khelo/ui/flow/matches/match_detail/components/match_detail_overs_view.dart'; import 'package:khelo/ui/flow/matches/match_detail/components/match_detail_scorecard_view.dart'; import 'package:khelo/ui/flow/matches/match_detail/components/match_detail_squad_view.dart'; -import 'package:rxdart/rxdart.dart'; part 'match_detail_tab_view_model.freezed.dart'; @@ -54,15 +54,13 @@ class MatchDetailTabViewNotifier extends StateNotifier { void _loadMatchesAndInning() { try { state = state.copyWith(loading: true); - final matchInningStream = Rx.combineLatest2( + final matchInningStream = combineLatest2( _matchService.getMatchStreamById(_matchId), _inningService.getInningsStreamByMatchId(matchId: _matchId), - (match, innings) => (match: match, innings: innings), ); - matchStreamSubscription = matchInningStream.listen((data) { - final match = data.match; - final innings = data.innings; + final match = data.$1; + final innings = data.$2; state = state.copyWith(match: match); final firstInning = innings .where((element) => diff --git a/khelo/lib/ui/flow/score_board/score_board_view_model.dart b/khelo/lib/ui/flow/score_board/score_board_view_model.dart index d6a8d444..722d99f3 100644 --- a/khelo/lib/ui/flow/score_board/score_board_view_model.dart +++ b/khelo/lib/ui/flow/score_board/score_board_view_model.dart @@ -7,12 +7,12 @@ import 'package:data/errors/app_error.dart'; import 'package:data/service/match/match_service.dart'; import 'package:data/service/innings/inning_service.dart'; import 'package:data/service/ball_score/ball_score_service.dart'; +import 'package:data/utils/combine_latest.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:khelo/domain/extensions/context_extensions.dart'; import 'package:khelo/ui/flow/score_board/components/select_player_sheet.dart'; -import 'package:rxdart/rxdart.dart'; part 'score_board_view_model.freezed.dart'; @@ -30,7 +30,7 @@ class ScoreBoardViewNotifier extends StateNotifier { final InningsService _inningService; final BallScoreService _ballScoreService; late StreamSubscription _matchStreamSubscription; - late StreamSubscription> _ballScoreStreamSubscription; + late StreamSubscription>? _ballScoreStreamSubscription; final StreamController _matchStreamController = StreamController(); String? matchId; @@ -59,14 +59,13 @@ class ScoreBoardViewNotifier extends StateNotifier { void _loadMatchesAndInning() { try { state = state.copyWith(loading: true); - final matchInningStream = Rx.combineLatest2( + final matchInningStream = combineLatest2( _matchService.getMatchStreamById(matchId!), _inningService.getInningsStreamByMatchId(matchId: matchId!), - (match, innings) => {'match': match, 'innings': innings}, ).asyncMap((data) async { try { - MatchModel match = data['match'] as MatchModel; - List innings = data['innings'] as List; + MatchModel match = data.$1; + List innings = data.$2; final previousMatch = state.match; final isMatchChanged = state.match != match; state = state.copyWith(match: match, error: null); @@ -137,62 +136,57 @@ class ScoreBoardViewNotifier extends StateNotifier { } try { state = state.copyWith(ballScoreQueryListenerSet: true); - final ballScoreStream = Rx.combineLatest2( - _matchStreamController.stream, - _loadBallScoresStream(currentInningId, otherInningId), - (match, scores) { - List currentScoreList = - state.currentScoresList.toList(); - List previousScoreList = - state.currentScoresList.toList(); - - for (var score in scores) { - if (score.type == DocumentChangeType.added) { - if (score.ballScore.inning_id == state.currentInning?.id && - !currentScoreList - .map((e) => e.id) - .contains(score.ballScore.id)) { - currentScoreList.add(score.ballScore); - } else if (score.ballScore.inning_id == state.otherInning?.id && - !previousScoreList - .map((e) => e.id) - .contains(score.ballScore.id)) { - previousScoreList.add(score.ballScore); - } - } else if (score.type == DocumentChangeType.removed) { - if (score.ballScore.inning_id == state.currentInning?.id && - currentScoreList - .map((e) => e.id) - .contains(score.ballScore.id)) { + final ballScoreStream = combineLatest2(_matchStreamController.stream, + _loadBallScoresStream(currentInningId, otherInningId)) + .map((data) { + final scores = data.$2; + + List currentScoreList = + state.currentScoresList.toList(); + List previousScoreList = + state.currentScoresList.toList(); + + for (var score in scores) { + if (score.type == DocumentChangeType.added) { + if (score.ballScore.inning_id == state.currentInning?.id && + !currentScoreList + .map((e) => e.id) + .contains(score.ballScore.id)) { + currentScoreList.add(score.ballScore); + } else if (score.ballScore.inning_id == state.otherInning?.id && + !previousScoreList + .map((e) => e.id) + .contains(score.ballScore.id)) { + previousScoreList.add(score.ballScore); + } + } else if (score.type == DocumentChangeType.removed) { + if (score.ballScore.inning_id == state.currentInning?.id && currentScoreList - .removeWhere((element) => element.id == score.ballScore.id); - } else if (score.ballScore.inning_id == state.otherInning?.id && - previousScoreList - .map((e) => e.id) - .contains(score.ballScore.id)) { + .map((e) => e.id) + .contains(score.ballScore.id)) { + currentScoreList + .removeWhere((element) => element.id == score.ballScore.id); + } else if (score.ballScore.inning_id == state.otherInning?.id && previousScoreList - .removeWhere((element) => element.id == score.ballScore.id); - } + .map((e) => e.id) + .contains(score.ballScore.id)) { + previousScoreList + .removeWhere((element) => element.id == score.ballScore.id); } } + } - currentScoreList.sort( - (a, b) => a.time.compareTo(b.time), - ); - - previousScoreList.sort( - (a, b) => a.time.compareTo(b.time), - ); - state = state.copyWith( - currentScoresList: currentScoreList, - previousScoresList: previousScoreList, - ballScoreQueryListenerSet: true, - loading: false, - error: null); - return scores; - }, - ); + currentScoreList.sort((a, b) => a.time.compareTo(b.time)); + previousScoreList.sort((a, b) => a.time.compareTo(b.time)); + state = state.copyWith( + currentScoresList: currentScoreList, + previousScoresList: previousScoreList, + ballScoreQueryListenerSet: true, + loading: false, + error: null); + return scores; + }); _ballScoreStreamSubscription = ballScoreStream.listen((scores) { if (state.isMatchUpdated) { _configureScoringDetails( @@ -1135,7 +1129,7 @@ class ScoreBoardViewNotifier extends StateNotifier { _cancelStreamSubscription() async { await _matchStreamSubscription.cancel(); - await _ballScoreStreamSubscription.cancel(); + await _ballScoreStreamSubscription?.cancel(); await _matchStreamController.close(); } diff --git a/khelo/lib/ui/flow/team/detail/team_detail_screen.dart b/khelo/lib/ui/flow/team/detail/team_detail_screen.dart index e228f381..4c13ba7b 100644 --- a/khelo/lib/ui/flow/team/detail/team_detail_screen.dart +++ b/khelo/lib/ui/flow/team/detail/team_detail_screen.dart @@ -120,7 +120,7 @@ class _TeamDetailScreenState extends ConsumerState { if (state.error != null) { return ErrorScreen( error: state.error, - onRetryTap: notifier.loadTeamById, + onRetryTap: notifier.onResume, ); } @@ -139,7 +139,7 @@ class _TeamDetailScreenState extends ConsumerState { Widget _tabView(BuildContext context) { return Padding( - padding: const EdgeInsets.symmetric(horizontal: 16.0), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9), child: Row( children: [ TabButton( @@ -187,25 +187,18 @@ class _TeamDetailScreenState extends ConsumerState { title: context.l10n.common_edit_team_title, onTap: () async { context.pop(); - bool? isUpdated = - await AppRoute.addTeam(team: state.team).push(context); - if (isUpdated == true && context.mounted) { - notifier.loadTeamById(); - } + AppRoute.addTeam(team: state.team).push(context); }, ), BottomSheetAction( title: context.l10n.add_match_screen_title, - onTap: () async { + onTap: () { context.pop(); - bool? isUpdated = await AppRoute.addMatch( + AppRoute.addMatch( defaultTeam: (state.team?.players?.length ?? 0) >= 2 ? state.team : null) - .push(context); - if (isUpdated == true && context.mounted) { - notifier.loadTeamById(); - } + .push(context); }, ), ]); diff --git a/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart b/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart index 4a6dc0f1..9da0ba27 100644 --- a/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart +++ b/khelo/lib/ui/flow/team/detail/team_detail_view_model.dart @@ -1,6 +1,7 @@ +import 'dart:async'; + import 'package:data/api/match/match_model.dart'; import 'package:data/api/team/team_model.dart'; -import 'package:data/api/user/user_models.dart'; import 'package:data/service/match/match_service.dart'; import 'package:data/service/team/team_service.dart'; import 'package:data/storage/app_preferences.dart'; @@ -19,6 +20,8 @@ final teamDetailStateProvider = )); class TeamDetailViewNotifier extends StateNotifier { + late StreamSubscription _teamStreamSubscription; + late StreamSubscription _matchListStreamSubscription; final TeamService _teamService; final MatchService _matchService; String? teamId; @@ -32,38 +35,34 @@ class TeamDetailViewNotifier extends StateNotifier { } Future loadTeamById() async { - if (teamId == null) { - return; - } + if (teamId == null) return; - try { - state = state.copyWith(loading: state.team == null); - - final team = await _teamService.getTeamById(teamId!); + state = state.copyWith(loading: state.team == null); + _teamStreamSubscription = + _teamService.getTeamStreamById(teamId!).listen((team) { state = state.copyWith(team: team, loading: false); loadTeamMatches(); - } catch (e) { + }, onError: (e) { state = state.copyWith(loading: false, error: e); debugPrint( "TeamDetailViewNotifier: error while loading team by id -> $e"); - } + }); } Future loadTeamMatches() async { - if (state.team == null) { - return; - } - try { - state = state.copyWith(loading: state.matches == null); - final matches = await _matchService - .getMatchesByTeamId(state.team!.id ?? "INVALID ID"); + if (state.team == null) return; + + state = state.copyWith(loading: state.matches == null); + _matchListStreamSubscription = _matchService + .getMatchesByTeamId(state.team!.id ?? "INVALID ID") + .listen((matches) { final teamStat = _calculateTeamStat(matches); state = state.copyWith(matches: matches, teamStat: teamStat, loading: false); - } catch (e) { + }, onError: (e) { debugPrint( "TeamDetailViewNotifier: error while loading team matches -> $e"); - } + }); } TeamStat _calculateTeamStat(List matches) { @@ -188,17 +187,24 @@ class TeamDetailViewNotifier extends StateNotifier { ); } - void updateTeamMember(List members) { - state = state.copyWith( - team: state.team - ?.copyWith(players: [...state.team?.players ?? [], ...members])); - } - void onTabChange(int tab) { if (state.selectedTab != tab) { state = state.copyWith(selectedTab: tab); } } + + onResume() { + _teamStreamSubscription.cancel(); + _matchListStreamSubscription.cancel(); + loadTeamById(); + } + + @override + void dispose() { + _teamStreamSubscription.cancel(); + _matchListStreamSubscription.cancel(); + super.dispose(); + } } @freezed diff --git a/khelo/lib/ui/flow/team/search_team/search_team_view_model.dart b/khelo/lib/ui/flow/team/search_team/search_team_view_model.dart index 4a60485f..0b58e110 100644 --- a/khelo/lib/ui/flow/team/search_team/search_team_view_model.dart +++ b/khelo/lib/ui/flow/team/search_team/search_team_view_model.dart @@ -15,6 +15,7 @@ final searchTeamViewStateProvider = }); class SearchTeamViewNotifier extends StateNotifier { + late StreamSubscription _streamSubscription; final TeamService _teamService; Timer? _debounce; List excludedIds = []; @@ -32,18 +33,17 @@ class SearchTeamViewNotifier extends StateNotifier { Future loadTeamList() async { state = state.copyWith(loading: true); - try { - final res = await _teamService.getUserOwnedTeams(); + _streamSubscription = _teamService.getUserOwnedTeams().listen((teams) { final filteredResult = - res.where((element) => !excludedIds.contains(element.id)).toList(); + teams.where((element) => !excludedIds.contains(element.id)).toList(); state = state.copyWith( userTeams: filteredResult, loading: false, error: null); - } catch (e) { + }, onError: (e) { state = state.copyWith(loading: false, error: e); debugPrint("SearchTeamViewNotifier: error while loading team list -> $e"); - } + }); } Future search(String searchKey) async { @@ -102,6 +102,7 @@ class SearchTeamViewNotifier extends StateNotifier { @override void dispose() { _debounce?.cancel(); + _streamSubscription.cancel(); super.dispose(); } } diff --git a/khelo/pubspec.lock b/khelo/pubspec.lock index 5471cd94..95fbd256 100644 --- a/khelo/pubspec.lock +++ b/khelo/pubspec.lock @@ -595,10 +595,10 @@ packages: dependency: transitive description: name: flutter_timezone - sha256: "06b35132c98fa188db3c4b654b7e1af7ccd01dfe12a004d58be423357605fb24" + sha256: b7448ff8a9e1350606727e40b3f314aa798a6a1cc07127eba58f09b98a66f03f url: "https://pub.dev" source: hosted - version: "1.0.8" + version: "2.0.0" flutter_web_plugins: dependency: transitive description: flutter @@ -832,10 +832,18 @@ packages: dependency: transitive description: name: js - sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf + sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 url: "https://pub.dev" source: hosted - version: "0.7.1" + version: "0.6.7" + js_interop: + dependency: transitive + description: + name: js_interop + sha256: "7ec859c296958ccea34dc770504bd3ff4ae52fdd9e7eeb2bacc7081ad476a1f5" + url: "https://pub.dev" + source: hosted + version: "0.0.1" json_annotation: dependency: transitive description: @@ -1101,7 +1109,7 @@ packages: source: hosted version: "2.3.10" rxdart: - dependency: "direct main" + dependency: transitive description: name: rxdart sha256: "0c7c0cedd93788d996e33041ffecda924cc54389199cde4e6a34b440f50044cb" diff --git a/khelo/pubspec.yaml b/khelo/pubspec.yaml index 2f28f982..ebcd58bc 100644 --- a/khelo/pubspec.yaml +++ b/khelo/pubspec.yaml @@ -40,8 +40,6 @@ dependencies: path: ../data shared_preferences: ^2.2.2 - rxdart: ^0.27.7 - collection: any # UI