diff --git a/.fvm/fvm_config.json b/.fvm/fvm_config.json index d8abe1b9..1726d93d 100644 --- a/.fvm/fvm_config.json +++ b/.fvm/fvm_config.json @@ -1,4 +1,3 @@ { - "flutterSdkVersion": "3.13.9", - "flavors": {} + "flutterSdkVersion": "3.13.9" } \ No newline at end of file diff --git a/.fvmrc b/.fvmrc new file mode 100644 index 00000000..05b430ce --- /dev/null +++ b/.fvmrc @@ -0,0 +1,3 @@ +{ + "flutter": "3.13.9" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1be2d875..7040cb04 100644 --- a/.gitignore +++ b/.gitignore @@ -46,4 +46,6 @@ app.*.map.json /android/app/release # fvm -.fvm/flutter_sdk \ No newline at end of file + +# FVM Version Cache +.fvm/ \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index f285aa4a..0e6ea20d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,9 +1,9 @@ { - "dart.flutterSdkPath": ".fvm/flutter_sdk", - "search.exclude": { - "**/.fvm": true - }, - "files.watcherExclude": { - "**/.fvm": true - } + "dart.flutterSdkPath": ".fvm/flutter_sdk", + "search.exclude": { + "**/.fvm": true + }, + "files.watcherExclude": { + "**/.fvm": true + } } \ No newline at end of file diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig index 592ceee8..ec97fc6f 100644 --- a/ios/Flutter/Debug.xcconfig +++ b/ios/Flutter/Debug.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig index 592ceee8..c4855bfe 100644 --- a/ios/Flutter/Release.xcconfig +++ b/ios/Flutter/Release.xcconfig @@ -1 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile new file mode 100644 index 00000000..ba7f94f9 --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,44 @@ +# Uncomment this line to define a global platform for your project +platform :ios, '11.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + # target 'RunnerTests' do + # inherit! :search_paths + # end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/ios/Podfile.lock b/ios/Podfile.lock new file mode 100644 index 00000000..6f56688f --- /dev/null +++ b/ios/Podfile.lock @@ -0,0 +1,23 @@ +PODS: + - Flutter (1.0.0) + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - Flutter (from `Flutter`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + +SPEC CHECKSUMS: + Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 + shared_preferences_foundation: b4c3b4cddf1c21f02770737f147a3f5da9d39695 + +PODFILE CHECKSUM: f567b6369f8842e77ccf6611a4baf3e2181f3f05 + +COCOAPODS: 1.15.2 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 73cf3f6d..5f12042d 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 4513869A18E4B7761A71BE55 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F242A4A329A8BBE48105CF49 /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; @@ -32,6 +33,8 @@ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 5577F3703A4671A8C48E6EBF /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 66CDC8FD2A5B01486CD8D5B4 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; @@ -42,6 +45,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C40EE2C3D449DAC26263639A /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + F242A4A329A8BBE48105CF49 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -49,12 +54,21 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 4513869A18E4B7761A71BE55 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 73474F1D49D6740B01ADDC34 /* Frameworks */ = { + isa = PBXGroup; + children = ( + F242A4A329A8BBE48105CF49 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -72,6 +86,8 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, + DE0F3B9FCEE7124AD92F0727 /* Pods */, + 73474F1D49D6740B01ADDC34 /* Frameworks */, ); sourceTree = ""; }; @@ -98,6 +114,17 @@ path = Runner; sourceTree = ""; }; + DE0F3B9FCEE7124AD92F0727 /* Pods */ = { + isa = PBXGroup; + children = ( + C40EE2C3D449DAC26263639A /* Pods-Runner.debug.xcconfig */, + 5577F3703A4671A8C48E6EBF /* Pods-Runner.release.xcconfig */, + 66CDC8FD2A5B01486CD8D5B4 /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -105,12 +132,14 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + FFBE5A628B5FE27037CCAAFE /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 0AB4AD3E27C9D4A94BD4259E /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -169,6 +198,23 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 0AB4AD3E27C9D4A94BD4259E /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -200,6 +246,28 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; + FFBE5A628B5FE27037CCAAFE /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata index 1d526a16..21a3cc14 100644 --- a/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/lib/data/exceptions/network_exception.dart b/lib/data/exceptions/network_exception.dart new file mode 100644 index 00000000..eca5b788 --- /dev/null +++ b/lib/data/exceptions/network_exception.dart @@ -0,0 +1,10 @@ +class NetworkException implements Exception { + final int statusCode; + final String? message; + + NetworkException({required this.statusCode, this.message}); + + @override + String toString() => + 'NetworkException: statusCode: $statusCode, message: $message'; +} diff --git a/lib/models/restaurant.dart b/lib/data/models/restaurant.dart similarity index 98% rename from lib/models/restaurant.dart rename to lib/data/models/restaurant.dart index 87c7aab5..f9d4e28b 100644 --- a/lib/models/restaurant.dart +++ b/lib/data/models/restaurant.dart @@ -55,11 +55,13 @@ class Review { final String? id; final int? rating; final User? user; + final String? text; const Review({ this.id, this.rating, this.user, + this.text, }); factory Review.fromJson(Map json) => _$ReviewFromJson(json); diff --git a/lib/models/restaurant.g.dart b/lib/data/models/restaurant.g.dart similarity index 98% rename from lib/models/restaurant.g.dart rename to lib/data/models/restaurant.g.dart index 3ed33f9a..bc0be0dd 100644 --- a/lib/models/restaurant.g.dart +++ b/lib/data/models/restaurant.g.dart @@ -42,12 +42,14 @@ Review _$ReviewFromJson(Map json) => Review( user: json['user'] == null ? null : User.fromJson(json['user'] as Map), + text: json['text'] as String?, ); Map _$ReviewToJson(Review instance) => { 'id': instance.id, 'rating': instance.rating, 'user': instance.user, + 'text': instance.text, }; Location _$LocationFromJson(Map json) => Location( diff --git a/lib/data/sources/shared_preferences_source.dart b/lib/data/sources/shared_preferences_source.dart new file mode 100644 index 00000000..fedf11c8 --- /dev/null +++ b/lib/data/sources/shared_preferences_source.dart @@ -0,0 +1,43 @@ +import 'dart:async'; + +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// This class is the implementation of the [SharedPreferencesRepository] interface. +/// It uses the [SharedPreferences] package to store the favorite restaurants. + +class SharedPreferencesSource extends SharedPreferencesRepository { + static const _key = 'favorite_restaurants'; + + final StreamController> _controller = + StreamController.broadcast(); + + @override + Future> getFavoriteRestaurants() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getStringList(_key) ?? []; + } + + @override + Future toggleFavoriteRestaurant(String restaurantId) async { + final prefs = await SharedPreferences.getInstance(); + final favoriteRestaurants = prefs.getStringList(_key) ?? []; + if (favoriteRestaurants.contains(restaurantId)) { + favoriteRestaurants.remove(restaurantId); + } else { + favoriteRestaurants.add(restaurantId); + } + await prefs.setStringList(_key, favoriteRestaurants); + _controller.add(favoriteRestaurants); + } + + @override + Stream> watchFavoriteRestaurants() { + _controller.addStream(Stream.fromFuture(getFavoriteRestaurants())); + return _controller.stream; + } + + void dispose() { + _controller.close(); + } +} diff --git a/lib/repositories/yelp_repository.dart b/lib/data/sources/yelp_source.dart similarity index 70% rename from lib/repositories/yelp_repository.dart rename to lib/data/sources/yelp_source.dart index f251d7b4..33cd08d3 100644 --- a/lib/repositories/yelp_repository.dart +++ b/lib/data/sources/yelp_source.dart @@ -1,13 +1,15 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; -import 'package:restaurantour/models/restaurant.dart'; +import 'package:restaurantour/data/exceptions/network_exception.dart'; +import 'package:restaurantour/data/models/restaurant.dart'; -const _apiKey = ''; +const _apiKey = + 'wfYIpeyetAPJbQYg5ITUE4wxzqCvoEQM5FQyW9Xq4SGJG52vkefWY_Irq9yg_TKpXRYJUgTO48W_fVXReEABY919sT74bHoCAyNH4b0kTe94rmEWFWNo1GjFxUXjZXYx'; -class YelpRepository { +class YelpSource { late Dio dio; - YelpRepository({ + YelpSource({ @visibleForTesting Dio? dio, }) : dio = dio ?? Dio( @@ -29,7 +31,7 @@ class YelpRepository { /// { /// "id": "faPVqws-x-5k2CQKDNtHxw", /// "name": "Yardbird Southern Table & Bar", - /// "price": "$$", + /// "price": "2", /// "rating": 4.5, /// "photos": [ /// "https:///s3-media4.fl.yelpcdn.com/bphoto/_zXRdYX4r1OBfF86xKMbDw/o.jpg" @@ -58,22 +60,33 @@ class YelpRepository { /// } /// } /// - Future getRestaurants({int offset = 0}) async { + + Future?> getRestaurants({int offset = 0}) async { try { final response = await dio.post>( '/v3/graphql', data: _getQuery(offset), ); - return RestaurantQueryResult.fromJson(response.data!['data']['search']); + + if (response.statusCode != null && response.statusCode! >= 400) { + throw NetworkException( + statusCode: response.statusCode!, + message: response.statusMessage, + ); + } else if (response.statusCode != null) { + return RestaurantQueryResult.fromJson(response.data!['data']['search']) + .restaurants; + } } catch (e) { - return null; + throw Exception('Failed to get restaurants: $e'); } + return null; } String _getQuery(int offset) { return ''' query getRestaurants { - search(location: "Las Vegas", limit: 20, offset: $offset) { + search(location: "Las Vegas", limit: 15, offset: $offset) { total business { id @@ -84,6 +97,7 @@ query getRestaurants { reviews { id rating + text user { id image_url diff --git a/lib/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart new file mode 100644 index 00000000..b575c0a8 --- /dev/null +++ b/lib/dependency_injection/di_locator.dart @@ -0,0 +1,78 @@ +import 'package:flutter/foundation.dart'; +import 'package:get_it/get_it.dart'; +import 'package:restaurantour/data/sources/shared_preferences_source.dart'; +import 'package:restaurantour/data/sources/yelp_source.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart'; + +final locator = GetIt.instance; + +void setupLocator() { + // Sources + locator.registerLazySingleton(() => YelpSource()); + locator.registerLazySingleton( + () => SharedPreferencesSource(), + ); + + // Repositories + locator.registerLazySingleton( + () => RestaurantRepositoryImpl( + locator(), + ), + ); + locator.registerLazySingleton( + () => SharedPreferencesRepositoryImpl( + locator(), + ), + ); + + // UseCases + locator.registerFactory( + () => GetRestaurantsUseCase( + locator(), + ), + ); + locator.registerFactory( + () => ToggleFavoriteRestaurantUseCase( + locator(), + ), + ); + locator.registerFactory( + () => WatchFavoriteRestaurantsUseCase( + locator(), + ), + ); + locator.registerFactory( + () => GetRestaurantFavoriteStatusUseCase( + locator(), + ), + ); + + // ViewModels + locator.registerLazySingleton( + () => RestaurantListViewModel( + locator(), + locator(), + ), + ); + locator.registerFactory( + () => RestaurantDetailViewModel( + locator(), + locator(), + ), + ); +} + +/// Regisers an object of type T +/// +/// only available for testing +@visibleForTesting +void testRegister(T object) { + locator.registerSingleton(object); +} diff --git a/lib/design_system/open_status_indicator.dart b/lib/design_system/open_status_indicator.dart new file mode 100644 index 00000000..30e6847d --- /dev/null +++ b/lib/design_system/open_status_indicator.dart @@ -0,0 +1,27 @@ +import 'package:flutter/material.dart'; + +class OpenStatusIndicator extends StatelessWidget { + const OpenStatusIndicator({ + Key? key, + required this.isOpen, + }) : super(key: key); + final bool isOpen; + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Text(isOpen ? 'Open' : 'Closed'), + const SizedBox(width: 4), + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isOpen ? Colors.green : Colors.red, + ), + ), + ], + ); + } +} diff --git a/lib/design_system/restaurant_address.dart b/lib/design_system/restaurant_address.dart new file mode 100644 index 00000000..df9085be --- /dev/null +++ b/lib/design_system/restaurant_address.dart @@ -0,0 +1,37 @@ +import 'package:flutter/material.dart'; + +class RestaurantAddress extends StatelessWidget { + const RestaurantAddress({ + Key? key, + required this.address, + }) : super(key: key); + final String address; + + @override + Widget build(BuildContext context) { + return Align( + alignment: Alignment.topLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Address', + style: TextStyle( + fontSize: 12, + ), + ), + const SizedBox( + height: 12, + ), + Text( + address, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ); + } +} diff --git a/lib/design_system/restaurant_details.dart b/lib/design_system/restaurant_details.dart new file mode 100644 index 00000000..b59acf67 --- /dev/null +++ b/lib/design_system/restaurant_details.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +class RestaurantDetails extends StatelessWidget { + final String price; + final String category; + + const RestaurantDetails({ + Key? key, + required this.price, + required this.category, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return Row( + children: [ + Text(price), + const SizedBox(width: 4), + Text(category), + ], + ); + } +} diff --git a/lib/design_system/restaurant_list_tile.dart b/lib/design_system/restaurant_list_tile.dart new file mode 100644 index 00000000..b48658f4 --- /dev/null +++ b/lib/design_system/restaurant_list_tile.dart @@ -0,0 +1,62 @@ +import 'package:flutter/material.dart'; +import 'package:restaurantour/design_system/open_status_indicator.dart'; +import 'package:restaurantour/design_system/restaurant_details.dart'; +import 'package:restaurantour/design_system/restaurant_stars.dart'; + +class RestaurantListTile extends StatelessWidget { + final String imageUrl; + final String name; + final String priceRange; + final String category; + final double rating; + final bool isOpen; + final VoidCallback? onTap; + + const RestaurantListTile({ + Key? key, + required this.imageUrl, + required this.name, + required this.priceRange, + required this.category, + required this.rating, + required this.isOpen, + this.onTap, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: ListTile( + leading: imageUrl.isEmpty + ? const SizedBox.shrink() + : Image.network( + imageUrl, + width: 88, + height: 88, + fit: BoxFit.cover, + ), + title: Text(name), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + RestaurantDetails( + price: priceRange, + category: category, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + RestaurantStars(rating: rating), + OpenStatusIndicator(isOpen: isOpen), + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/design_system/restaurant_rating.dart b/lib/design_system/restaurant_rating.dart new file mode 100644 index 00000000..03565e3f --- /dev/null +++ b/lib/design_system/restaurant_rating.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +class RestaurantRating extends StatelessWidget { + const RestaurantRating({ + Key? key, + required this.rating, + }) : super(key: key); + final double rating; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Overall Rating:', + style: TextStyle( + fontSize: 14, + ), + ), + const SizedBox( + height: 8, + ), + Row( + children: [ + Text( + rating.toString(), + style: const TextStyle( + fontSize: 28, + fontFamily: 'Lora', + fontWeight: FontWeight.bold, + ), + ), + const SizedBox( + width: 8, + ), + const Icon( + Icons.star, + color: Colors.amber, + ), + ], + ), + ], + ); + } +} diff --git a/lib/design_system/restaurant_stars.dart b/lib/design_system/restaurant_stars.dart new file mode 100644 index 00000000..bc1428cd --- /dev/null +++ b/lib/design_system/restaurant_stars.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; + +/// Represents the restaurant rating in only stars +class RestaurantStars extends StatelessWidget { + const RestaurantStars({ + Key? key, + required this.rating, + }) : super(key: key); + final double rating; + + @override + Widget build(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: List.generate( + 5, + (index) { + if (index < rating.round()) { + return const Icon( + Icons.star, + color: Colors.amber, + ); + } + return const SizedBox.shrink(); + }, + ), + ); + } +} diff --git a/lib/domain/exceptions/mapper_exception.dart b/lib/domain/exceptions/mapper_exception.dart new file mode 100644 index 00000000..3db59fc0 --- /dev/null +++ b/lib/domain/exceptions/mapper_exception.dart @@ -0,0 +1,10 @@ +class MapperException implements Exception { + final String message; + + MapperException(this.message); + + @override + String toString() { + return 'Error mapping from:$From to: $To message: $message'; + } +} diff --git a/lib/domain/restaurant_mapper.dart b/lib/domain/restaurant_mapper.dart new file mode 100644 index 00000000..a6e87e7d --- /dev/null +++ b/lib/domain/restaurant_mapper.dart @@ -0,0 +1,50 @@ +import 'package:restaurantour/domain/exceptions/mapper_exception.dart'; +import 'package:restaurantour/data/models/restaurant.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/entities/review_entity.dart'; +import 'package:restaurantour/domain/restaurants/entities/user_entity.dart'; + +/// Handles mapping from Restaurant model to Restaurant entity (local) +class RestaurantMapper { + // Maps the restaurant model to restaurant entity + static RestaurantEntity fromModel(Restaurant model) { + if (model.id == null || model.name == null || model.name!.isEmpty) { + throw MapperException('Invalid restaurant model'); + } + + final List reviews = model.reviews + ?.map( + (review) => ReviewEntity( + id: review.id ?? '', + userId: review.user?.id ?? '', + comment: review.text ?? '', + rating: review.rating ?? 0, + author: UserEntity( + id: review.user?.id ?? '', + name: review.user?.name ?? '', + profileImageUrl: review.user?.imageUrl ?? + 'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/batman_hero_avatar_comics-512.png', + ), + ), + ) + .toList() ?? + []; + + return RestaurantEntity( + id: model.id ?? '', + name: model.name ?? '', + price: model.price ?? '', + rating: model.rating ?? 0.0, + heroImage: model.photos?.first ?? '', + isOpen: model.isOpen, + reviews: reviews, + address: model.location?.formattedAddress ?? '', + category: model.categories?.first.title ?? '', + ); + } + + // Maps the restaurant model list to restaurant entity list + static List fromModelList(List modelList) { + return modelList.map((model) => fromModel(model)).toList(); + } +} diff --git a/lib/domain/restaurants/entities/restaurant_entity.dart b/lib/domain/restaurants/entities/restaurant_entity.dart new file mode 100644 index 00000000..1d760dbe --- /dev/null +++ b/lib/domain/restaurants/entities/restaurant_entity.dart @@ -0,0 +1,54 @@ +import 'package:restaurantour/domain/restaurants/entities/review_entity.dart'; + +class RestaurantEntity { + final String id; + final String name; + final String heroImage; + final String price; + final double rating; + final String category; + final String address; + final bool isOpen; + final List reviews; + + const RestaurantEntity({ + required this.id, + required this.name, + required this.heroImage, + required this.price, + required this.rating, + required this.category, + required this.address, + required this.isOpen, + required this.reviews, + }); + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is RestaurantEntity && + other.id == id && + other.name == name && + other.heroImage == heroImage && + other.price == price && + other.rating == rating && + other.category == category && + other.address == address && + other.isOpen == isOpen && + other.reviews == reviews; + } + + @override + int get hashCode { + return id.hashCode ^ + name.hashCode ^ + heroImage.hashCode ^ + price.hashCode ^ + rating.hashCode ^ + category.hashCode ^ + address.hashCode ^ + isOpen.hashCode ^ + reviews.hashCode; + } +} diff --git a/lib/domain/restaurants/entities/review_entity.dart b/lib/domain/restaurants/entities/review_entity.dart new file mode 100644 index 00000000..0c34360a --- /dev/null +++ b/lib/domain/restaurants/entities/review_entity.dart @@ -0,0 +1,38 @@ +import 'package:restaurantour/domain/restaurants/entities/user_entity.dart'; + +class ReviewEntity { + final String id; + final String userId; + final String comment; + final int rating; + final UserEntity author; + + ReviewEntity({ + required this.id, + required this.userId, + required this.comment, + required this.rating, + required this.author, + }); + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is ReviewEntity && + other.id == id && + other.userId == userId && + other.comment == comment && + other.rating == rating && + other.author == author; + } + + @override + int get hashCode { + return id.hashCode ^ + userId.hashCode ^ + comment.hashCode ^ + rating.hashCode ^ + author.hashCode; + } +} diff --git a/lib/domain/restaurants/entities/user_entity.dart b/lib/domain/restaurants/entities/user_entity.dart new file mode 100644 index 00000000..1f44cc7e --- /dev/null +++ b/lib/domain/restaurants/entities/user_entity.dart @@ -0,0 +1,26 @@ +class UserEntity { + final String id; + final String name; + final String profileImageUrl; + + const UserEntity({ + required this.id, + required this.name, + required this.profileImageUrl, + }); + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is UserEntity && + other.id == id && + other.name == name && + other.profileImageUrl == profileImageUrl; + } + + @override + int get hashCode { + return id.hashCode ^ name.hashCode ^ profileImageUrl.hashCode; + } +} diff --git a/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart b/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart new file mode 100644 index 00000000..d6d13754 --- /dev/null +++ b/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart @@ -0,0 +1,32 @@ +import 'package:restaurantour/domain/exceptions/mapper_exception.dart'; +import 'package:restaurantour/data/sources/yelp_source.dart'; +import 'package:restaurantour/domain/restaurant_mapper.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart'; + +class RestaurantRepositoryImpl implements RestaurantsRepository { + final YelpSource _yelpSource; + RestaurantRepositoryImpl(this._yelpSource); + + @override + Future> getRestaurants(int offset) async { + // TODO(jvelezos): Remove this if clause to enable pagination + if (offset > 45) { + //wont call api to prevent exceeding limit + return Future.value([]); + } + + final result = await _yelpSource.getRestaurants(offset: offset); + if (result == null) { + throw Exception('Failed to fetch restaurants'); + } + + final restaurantEntities = RestaurantMapper.fromModelList(result); + + if (restaurantEntities.isEmpty) { + throw MapperException('Failed to map restaurants'); + } + + return RestaurantMapper.fromModelList(result); + } +} diff --git a/lib/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart b/lib/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart new file mode 100644 index 00000000..0f65ab86 --- /dev/null +++ b/lib/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart @@ -0,0 +1,22 @@ +import 'package:restaurantour/data/sources/shared_preferences_source.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; + +class SharedPreferencesRepositoryImpl implements SharedPreferencesRepository { + final SharedPreferencesSource _sharedPreferencesRepository; + SharedPreferencesRepositoryImpl(this._sharedPreferencesRepository); + + @override + Future toggleFavoriteRestaurant(String restaurantId) { + return _sharedPreferencesRepository.toggleFavoriteRestaurant(restaurantId); + } + + @override + Future> getFavoriteRestaurants() { + return _sharedPreferencesRepository.getFavoriteRestaurants(); + } + + @override + Stream> watchFavoriteRestaurants() { + return _sharedPreferencesRepository.watchFavoriteRestaurants(); + } +} diff --git a/lib/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart b/lib/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart new file mode 100644 index 00000000..00b94bbc --- /dev/null +++ b/lib/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart @@ -0,0 +1,5 @@ +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; + +abstract class RestaurantsRepository { + Future> getRestaurants(int offset); +} diff --git a/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart b/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart new file mode 100644 index 00000000..68dea69a --- /dev/null +++ b/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart @@ -0,0 +1,5 @@ +abstract class SharedPreferencesRepository { + Future toggleFavoriteRestaurant(String restaurantId); + Future> getFavoriteRestaurants(); + Stream> watchFavoriteRestaurants(); +} diff --git a/lib/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart b/lib/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart new file mode 100644 index 00000000..b4c4a7b1 --- /dev/null +++ b/lib/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart @@ -0,0 +1,14 @@ +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; + +class GetRestaurantFavoriteStatusUseCase { + final SharedPreferencesRepository _sharedPreferencesRepository; + + GetRestaurantFavoriteStatusUseCase(this._sharedPreferencesRepository); + + Future call(String restaurantId) async { + final List favoriteRestaurants = + await _sharedPreferencesRepository.getFavoriteRestaurants(); + + return favoriteRestaurants.contains(restaurantId); + } +} diff --git a/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart new file mode 100644 index 00000000..8c82e27a --- /dev/null +++ b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart @@ -0,0 +1,12 @@ +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart'; + +class GetRestaurantsUseCase { + final RestaurantsRepository _restaurantsRepository; + + GetRestaurantsUseCase(this._restaurantsRepository); + + Future> call(int? offset) { + return _restaurantsRepository.getRestaurants(offset ?? 0); + } +} diff --git a/lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart b/lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart new file mode 100644 index 00000000..b98cec50 --- /dev/null +++ b/lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart @@ -0,0 +1,11 @@ +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; + +class ToggleFavoriteRestaurantUseCase { + final SharedPreferencesRepository _preferencesRepository; + + ToggleFavoriteRestaurantUseCase(this._preferencesRepository); + + Future call(String restaurantId) async { + await _preferencesRepository.toggleFavoriteRestaurant(restaurantId); + } +} diff --git a/lib/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart b/lib/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart new file mode 100644 index 00000000..0af5ee88 --- /dev/null +++ b/lib/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart @@ -0,0 +1,13 @@ +import 'dart:async'; + +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; + +class WatchFavoriteRestaurantsUseCase { + final SharedPreferencesRepository _preferencesRepository; + + WatchFavoriteRestaurantsUseCase(this._preferencesRepository); + + Stream> call() { + return _preferencesRepository.watchFavoriteRestaurants(); + } +} diff --git a/lib/main.dart b/lib/main.dart index c6ce7473..f8364ca0 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,57 +1,35 @@ import 'package:flutter/material.dart'; -import 'package:restaurantour/repositories/yelp_repository.dart'; +import 'package:restaurantour/dependency_injection/di_locator.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_page.dart'; void main() { + setupLocator(); runApp(const Restaurantour()); } class Restaurantour extends StatelessWidget { - // This widget is the root of your application. const Restaurantour({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'RestauranTour', + debugShowCheckedModeBanner: false, theme: ThemeData( visualDensity: VisualDensity.adaptivePlatformDensity, - ), - home: const HomePage(), - ); - } -} - -class HomePage extends StatelessWidget { - const HomePage({Key? key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Restaurantour'), - ElevatedButton( - child: const Text('Fetch Restaurants'), - onPressed: () async { - final yelpRepo = YelpRepository(); - - try { - final result = await yelpRepo.getRestaurants(); - if (result != null) { - print('Fetched ${result.restaurants!.length} restaurants'); - } else { - print('No restaurants fetched'); - } - } catch (e) { - print('Failed to fetch restaurants: $e'); - } - }, - ), - ], + appBarTheme: const AppBarTheme( + backgroundColor: Colors.white, + elevation: 0, + iconTheme: IconThemeData(color: Colors.black), + titleTextStyle: TextStyle( + color: Colors.black, + fontFamily: 'Lora', + fontSize: 18, + fontWeight: FontWeight.bold, + ), ), ), + home: const RestaurantListPage(), ); } } diff --git a/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart new file mode 100644 index 00000000..32f0ac85 --- /dev/null +++ b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart @@ -0,0 +1,195 @@ +import 'package:flutter/material.dart'; +import 'package:restaurantour/dependency_injection/di_locator.dart'; +import 'package:restaurantour/design_system/open_status_indicator.dart'; +import 'package:restaurantour/design_system/restaurant_address.dart'; +import 'package:restaurantour/design_system/restaurant_details.dart'; +import 'package:restaurantour/design_system/restaurant_rating.dart'; +import 'package:restaurantour/design_system/restaurant_stars.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart'; +import 'package:provider/provider.dart'; +import 'package:restaurantour/presentation/utils/constants.dart'; + +class RestaurantDetailPage extends StatelessWidget { + const RestaurantDetailPage({ + Key? key, + required this.restaurant, + }) : super(key: key); + final RestaurantEntity restaurant; + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider( + create: (context) => + locator()..init(restaurant), + builder: (context, child) { + return Consumer( + builder: (context, viewModel, child) { + return Scaffold( + appBar: AppBar( + title: Text( + restaurant.name, + ), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + // Navigate back to the previous page + Navigator.pop(context); + }, + ), + actions: [ + IconButton( + icon: Icon( + viewModel.isFavorite + ? Icons.favorite + : Icons.favorite_border, + ), + onPressed: () { + final priorStatus = viewModel.isFavorite; + // toggle the favorite status + viewModel.toggleFavorite(); + + // Show a snackbar to confirm the action + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + priorStatus + ? 'Removed from favorites' + : 'Added to favorites', + ), + ), + ); + }, + ), + ], + ), + body: SingleChildScrollView( + child: Column( + children: [ + // Display the hero image + Hero( + tag: restaurant.id, + child: Image.network( + restaurant.heroImage, + fit: BoxFit.cover, + height: 300, + width: double.infinity, + ), + ), + // Display the restaurant details + Padding( + padding: const EdgeInsets.all(Constants.detailSpacing), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + RestaurantDetails( + price: restaurant.price, + category: restaurant.category, + ), + OpenStatusIndicator(isOpen: restaurant.isOpen), + ], + ), + ), + const Padding( + padding: EdgeInsets.symmetric( + horizontal: Constants.detailSpacing, + ), + child: Divider( + color: Colors.grey, + ), + ), + // Display Address + Padding( + padding: const EdgeInsets.all(Constants.detailSpacing), + child: RestaurantAddress( + address: restaurant.address, + ), + ), + const Padding( + padding: EdgeInsets.symmetric( + horizontal: Constants.detailSpacing), + child: Divider( + color: Colors.grey, + ), + ), + // Display the restaurant rating + Padding( + padding: const EdgeInsets.all( + Constants.detailSpacing, + ), + child: RestaurantRating( + rating: restaurant.rating, + ), + ), + const Padding( + padding: EdgeInsets.symmetric( + horizontal: Constants.detailSpacing), + child: Divider( + color: Colors.grey, + ), + ), + Padding( + padding: const EdgeInsets.all(Constants.detailSpacing), + child: Align( + alignment: Alignment.topLeft, + child: Text( + '${restaurant.reviews.length} Reviews', + ), + ), + ), + // Display the restaurant reviews + Padding( + padding: const EdgeInsets.symmetric( + horizontal: Constants.detailSpacing, + ), + child: Column( + children: restaurant.reviews + .map( + (review) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + RestaurantStars(rating: restaurant.rating), + const SizedBox( + height: Constants.detailVerticalSpacing), + Text( + review.comment, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + const SizedBox( + height: Constants.detailVerticalSpacing), + Row( + children: [ + CircleAvatar( + backgroundImage: NetworkImage( + review.author.profileImageUrl, + ), + ), + const SizedBox( + width: 4, + ), + Text(review.author.name), + ], + ), + const SizedBox( + height: Constants.detailVerticalSpacing, + ), + const Divider( + color: Colors.grey, + ), + ], + ), + ) + .toList(), + ), + ), + ], + ), + ), + ); + }, + ); + }, + ); + } +} diff --git a/lib/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart new file mode 100644 index 00000000..eacae577 --- /dev/null +++ b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart @@ -0,0 +1,38 @@ +import 'package:flutter/foundation.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart'; + +class RestaurantDetailViewModel extends ChangeNotifier { + RestaurantDetailViewModel( + this._toggleFavoriteRestaurantUseCase, + this._getRestaurantFavoriteStatusUseCase, + ); + + final ToggleFavoriteRestaurantUseCase _toggleFavoriteRestaurantUseCase; + final GetRestaurantFavoriteStatusUseCase _getRestaurantFavoriteStatusUseCase; + + bool _isFavorite = false; + bool get isFavorite => _isFavorite; + + RestaurantEntity? _restaurant; + RestaurantEntity? get restaurant => _restaurant; + + init(RestaurantEntity restaurant) { + _restaurant = restaurant; + getFavoriteStatus(); + } + + void getFavoriteStatus() async { + if (_restaurant == null) return; + _isFavorite = await _getRestaurantFavoriteStatusUseCase(_restaurant!.id); + notifyListeners(); + } + + void toggleFavorite() async { + if (_restaurant == null) return; + await _toggleFavoriteRestaurantUseCase(_restaurant!.id); + _isFavorite = !_isFavorite; + notifyListeners(); + } +} diff --git a/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart b/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart new file mode 100644 index 00000000..714a5996 --- /dev/null +++ b/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart @@ -0,0 +1,174 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:restaurantour/dependency_injection/di_locator.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart'; +import 'package:restaurantour/design_system/restaurant_list_tile.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart'; +import 'package:restaurantour/presentation/utils/constants.dart'; + +class RestaurantListPage extends StatelessWidget { + const RestaurantListPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return DefaultTabController( + length: 2, + child: Scaffold( + appBar: AppBar( + title: const Text(Constants.restaurantListTitle), + bottom: const TabBar( + labelStyle: TextStyle( + fontFamily: 'OpenSans', + fontSize: 14, + ), + labelColor: Colors.black, + tabs: [ + Tab( + text: Constants.allRestaurantsTabTitle, + ), + Tab( + text: Constants.favoriteRestaurantsTabTitle, + ), + ], + ), + ), + body: ChangeNotifierProvider( + create: (context) => locator()..init(), + builder: (context, child) { + return Consumer( + builder: (context, viewModel, child) { + return const TabBarView( + children: [ + _AllRestaurantsTab(), + _MyFavoritesTab(), + ], + ); + }, + ); + }, + ), + ), + ); + } +} + +class _AllRestaurantsTab extends StatelessWidget { + const _AllRestaurantsTab({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final viewModel = Provider.of(context); + + if (viewModel.isLoading) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + if (viewModel.hasError) { + return const Center( + child: Text( + Constants.errorFetching, + ), + ); + } + final restaurants = viewModel.restaurants; + + return NotificationListener( + onNotification: (ScrollNotification scrollInfo) { + if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) { + viewModel.getRestaurants(); + return true; + } + return false; + }, + child: ListView.builder( + itemCount: restaurants.length, + itemBuilder: (context, index) { + final RestaurantEntity restaurant = viewModel.restaurants[index]; + return RestaurantListTile( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RestaurantDetailPage( + // Pass necessary data to the detail page + restaurant: restaurant, + ), + ), + ); + }, + imageUrl: restaurant.heroImage, + name: restaurant.name, + priceRange: restaurant.price, + rating: restaurant.rating, + isOpen: restaurant.isOpen, + category: restaurant.category, + ); + }, + ), + ); + } +} + +class _MyFavoritesTab extends StatelessWidget { + const _MyFavoritesTab({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + if (viewModel.isLoading) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + if (viewModel.hasError) { + return const Center( + child: Text( + Constants.errorFetching, + ), + ); + } + + final favoriteRestaurants = viewModel.restaurants + .where((restaurant) => + viewModel.favoriteRestaurants.contains(restaurant.id)) + .toList(); + + if (favoriteRestaurants.isEmpty) { + return const Center( + child: Text( + 'You have no favorite restaurants yet.', + ), + ); + } + return ListView.builder( + itemCount: favoriteRestaurants.length, + itemBuilder: (context, index) { + final RestaurantEntity restaurant = favoriteRestaurants[index]; + return RestaurantListTile( + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => RestaurantDetailPage( + // Pass necessary data to the detail page + restaurant: restaurant, + ), + ), + ); + }, + imageUrl: restaurant.heroImage, + name: restaurant.name, + priceRange: restaurant.price, + rating: restaurant.rating, + isOpen: restaurant.isOpen, + category: restaurant.category, + ); + }, + ); + } +} diff --git a/lib/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart b/lib/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart new file mode 100644 index 00000000..7b8e3ef1 --- /dev/null +++ b/lib/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart @@ -0,0 +1,71 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; + +enum RestaurantListState { + loading, + loadingMore, + loaded, + error, +} + +class RestaurantListViewModel extends ChangeNotifier { + final GetRestaurantsUseCase _getRestaurantsUseCase; + final WatchFavoriteRestaurantsUseCase _watchFavoriteRestaurantsUseCase; + + RestaurantListViewModel( + this._getRestaurantsUseCase, + this._watchFavoriteRestaurantsUseCase, + ); + + final List _restaurants = []; + List get restaurants => _restaurants; + + List? _favoriteRestaurants; + List get favoriteRestaurants => _favoriteRestaurants ?? []; + + RestaurantListState _state = RestaurantListState.loading; + bool get hasError => _state == RestaurantListState.error; + bool get isLoading => _state == RestaurantListState.loading; + bool get hasData => _state == RestaurantListState.loaded; + + int _offset = 0; + + StreamSubscription>? _favoritesSubscription; + + void init() { + getRestaurants(); + _favoritesSubscription?.cancel(); + _favoritesSubscription = _watchFavoriteRestaurantsUseCase().listen((event) { + _favoriteRestaurants = event; + notifyListeners(); + }); + } + + @override + void dispose() { + super.dispose(); + _favoritesSubscription?.cancel(); + } + + Future getRestaurants() async { + try { + if (_state == RestaurantListState.loadingMore) return; + + _state = _offset == 0 + ? RestaurantListState.loading + : RestaurantListState.loadingMore; + + final result = await _getRestaurantsUseCase(_offset); + _restaurants.addAll(result); + _offset += result.length; + _state = RestaurantListState.loaded; + } catch (e) { + _state = RestaurantListState.error; + } + notifyListeners(); + } +} diff --git a/lib/presentation/utils/constants.dart b/lib/presentation/utils/constants.dart new file mode 100644 index 00000000..ee6a0258 --- /dev/null +++ b/lib/presentation/utils/constants.dart @@ -0,0 +1,12 @@ +class Constants { + // String constants + static const String errorFetching = + 'Oops, unable to fetch restaurants. Try again later.'; + static const String restaurantListTitle = 'Restaurant List'; + static const String allRestaurantsTabTitle = 'All Restaurants'; + static const String favoriteRestaurantsTabTitle = 'My Favorites'; + + // Double constants + static const double detailSpacing = 24.0; + static const double detailVerticalSpacing = 12.0; +} diff --git a/pubspec.lock b/pubspec.lock index 0b052c68..2a6f7dae 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,26 +5,26 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: ae92f5d747aee634b87f89d9946000c2de774be1d6ac3e58268224348cd0101a + sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 url: "https://pub.dev" source: hosted - version: "61.0.0" + version: "64.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: ea3d8652bda62982addfd92fdc2d0214e5f82e43325104990d4f4c4a2a313562 + sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" url: "https://pub.dev" source: hosted - version: "5.13.0" + version: "6.2.0" args: dependency: transitive description: name: args - sha256: "0bd9a99b6eb96f07af141f0eb53eace8983e8e5aa5de59777aca31684680ef22" + sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "2.4.2" async: dependency: transitive description: @@ -45,10 +45,10 @@ packages: dependency: transitive description: name: build - sha256: "3fbda25365741f8251b39f3917fb3c8e286a96fd068a5a242e11c2012d495777" + sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0" url: "https://pub.dev" source: hosted - version: "2.3.1" + version: "2.4.1" build_config: dependency: transitive description: @@ -61,18 +61,18 @@ packages: dependency: transitive description: name: build_daemon - sha256: "5f02d73eb2ba16483e693f80bee4f088563a820e47d1027d4cdfe62b5bb43e65" + sha256: "0343061a33da9c5810b2d6cee51945127d8f4c060b7fbdd9d54917f0a3feaaa1" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.0.1" build_resolvers: dependency: transitive description: name: build_resolvers - sha256: "6c4dd11d05d056e76320b828a1db0fc01ccd376922526f8e9d6c796a5adbac20" + sha256: "339086358431fa15d7eca8b6a36e5d783728cf025e559b834f4609a1fcfb7b0a" url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.4.2" build_runner: dependency: "direct dev" description: @@ -85,10 +85,10 @@ packages: dependency: transitive description: name: build_runner_core - sha256: f4d6244cc071ba842c296cb1c4ee1b31596b9f924300647ac7a1445493471a3f + sha256: "4ae8ffe5ac758da294ecf1802f2aff01558d8b1b00616aa7538ea9a8a5d50799" url: "https://pub.dev" source: hosted - version: "7.2.3" + version: "7.3.0" built_collection: dependency: transitive description: @@ -101,10 +101,10 @@ packages: dependency: transitive description: name: built_value - sha256: b6c9911b2d670376918d5b8779bc27e0e612a94ec3ff0343689e991d8d0a3b8a + sha256: fedde275e0a6b798c3296963c5cd224e3e1b55d0e478d5b7e65e6b540f363a0e url: "https://pub.dev" source: hosted - version: "8.1.4" + version: "8.9.1" characters: dependency: transitive description: @@ -113,22 +113,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.0" - charcode: - dependency: transitive - description: - name: charcode - sha256: fb98c0f6d12c920a02ee2d998da788bca066ca5f148492b7085ee23372b12306 - url: "https://pub.dev" - source: hosted - version: "1.3.1" checked_yaml: dependency: transitive description: name: checked_yaml - sha256: dd007e4fb8270916820a0d66e24f619266b60773cddd082c6439341645af2659 + sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "2.0.3" clock: dependency: transitive description: @@ -149,26 +141,26 @@ packages: dependency: transitive description: name: collection - sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.17.2" convert: dependency: transitive description: name: convert - sha256: f08428ad63615f96a27e34221c65e1a451439b5f26030f78d790f461c686d65d + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.1.1" crypto: dependency: transitive description: name: crypto - sha256: cf75650c66c0316274e21d7c43d3dea246273af5955bd94e8184837cd577575c + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.3" cupertino_icons: dependency: "direct main" description: @@ -181,18 +173,18 @@ packages: dependency: transitive description: name: dart_style - sha256: "1efa911ca7086affd35f463ca2fc1799584fb6aa89883cf0af8e3664d6a02d55" + sha256: "99e066ce75c89d6b29903d788a7bb9369cf754f7b24bf70bf4b6d6d6b26853b9" url: "https://pub.dev" source: hosted - version: "2.3.2" + version: "2.3.6" dio: dependency: "direct main" description: name: dio - sha256: "797e1e341c3dd2f69f2dad42564a6feff3bfb87187d05abb93b9609e6f1645c3" + sha256: "49af28382aefc53562459104f64d16b9dfd1e8ef68c862d5af436cc8356ce5a8" url: "https://pub.dev" source: hosted - version: "5.4.0" + version: "5.4.1" fake_async: dependency: transitive description: @@ -201,22 +193,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.1" + ffi: + dependency: transitive + description: + name: ffi + sha256: "7bf0adc28a23d395f19f3f1eb21dd7cfd1dd9f8e1c50051c069122e6853bc878" + url: "https://pub.dev" + source: hosted + version: "2.1.0" file: dependency: transitive description: name: file - sha256: b69516f2c26a5bcac4eee2e32512e1a5205ab312b3536c1c1227b2b942b5f9ad + sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" url: "https://pub.dev" source: hosted - version: "6.1.2" + version: "7.0.0" fixnum: dependency: transitive description: name: fixnum - sha256: "6a2ef17156f4dc49684f9d99aaf4a93aba8ac49f5eac861755f5730ddf6e2e4e" + sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "1.1.0" flutter: dependency: "direct main" description: flutter @@ -234,15 +234,20 @@ packages: dependency: "direct main" description: name: flutter_svg - sha256: d39e7f95621fc84376bc0f7d504f05c3a41488c562f4a8ad410569127507402c + sha256: "7b4ca6cf3304575fe9c8ec64813c8d02ee41d2afe60bcfe0678bcb5375d596a2" url: "https://pub.dev" source: hosted - version: "2.0.9" + version: "2.0.10+1" flutter_test: dependency: "direct dev" description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" frontend_server_client: dependency: transitive description: @@ -251,14 +256,22 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.0" + get_it: + dependency: "direct main" + description: + name: get_it + sha256: e6017ce7fdeaf218dc51a100344d8cb70134b80e28b760f8bb23c242437bafd7 + url: "https://pub.dev" + source: hosted + version: "7.6.7" glob: dependency: transitive description: name: glob - sha256: "8321dd2c0ab0683a91a51307fa844c6db4aa8e3981219b78961672aaab434658" + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "2.1.2" graphs: dependency: transitive description: @@ -267,38 +280,46 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.1" + http: + dependency: transitive + description: + name: http + sha256: "759d1a329847dd0f39226c688d3e06a6b8679668e350e2891a6474f8b4bb8525" + url: "https://pub.dev" + source: hosted + version: "1.1.0" http_multi_server: dependency: transitive description: name: http_multi_server - sha256: bfb651625e251a88804ad6d596af01ea903544757906addcb2dcdf088b5ea185 + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.2.1" http_parser: dependency: transitive description: name: http_parser - sha256: e362d639ba3bc07d5a71faebb98cde68c05bfbcfbbb444b60b6f60bb67719185 + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.0.2" io: dependency: transitive description: name: io - sha256: "0d4c73c3653ab85bf696d51a9657604c900a370549196a91f33e4c39af760852" + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "1.0.4" js: dependency: transitive description: name: js - sha256: d9bdfd70d828eeb352390f81b18d6a354ef2044aa28ef25682079797fa7cd174 + sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf url: "https://pub.dev" source: hosted - version: "0.6.3" + version: "0.7.1" json_annotation: dependency: "direct main" description: @@ -327,10 +348,10 @@ packages: dependency: transitive description: name: logging - sha256: "293ae2d49fd79d4c04944c3a26dfd313382d5f52e821ec57119230ae16031ad4" + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.2.0" matcher: dependency: transitive description: @@ -351,26 +372,42 @@ packages: dependency: transitive description: name: meta - sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e + sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" url: "https://pub.dev" source: hosted - version: "1.10.0" + version: "1.9.1" mime: dependency: transitive description: name: mime - sha256: fd5f81041e6a9fc9b9d7fa2cb8a01123f9f5d5d49136e06cb9dc7d33689529f4 + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.0.4" + mockito: + dependency: "direct dev" + description: + name: mockito + sha256: "6841eed20a7befac0ce07df8116c8b8233ed1f4486a7647c7fc5a02ae6163917" + url: "https://pub.dev" + source: hosted + version: "5.4.4" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" package_config: dependency: transitive description: name: package_config - sha256: a4d5ede5ca9c3d88a2fef1147a078570c861714c806485c596b109819135bc12 + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "2.1.0" path: dependency: transitive description: @@ -387,54 +424,158 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: "8bc9f22eee8690981c22aa7fc602f5c85b497a6fb2ceb35ee5a5e5ed85ad8170" + url: "https://pub.dev" + source: hosted + version: "2.2.1" petitparser: dependency: transitive description: name: petitparser - sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27 + sha256: cb3798bef7fc021ac45b308f4b51208a152792445cce0448c9a4ba5879dd8750 + url: "https://pub.dev" + source: hosted + version: "5.4.0" + platform: + dependency: transitive + description: + name: platform + sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" url: "https://pub.dev" source: hosted - version: "6.0.2" + version: "3.1.4" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" pool: dependency: transitive description: name: pool - sha256: "05955e3de2683e1746222efd14b775df7131139e07695dc8e24650f6b4204504" + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "1.5.1" + provider: + dependency: "direct main" + description: + name: provider + sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c + url: "https://pub.dev" + source: hosted + version: "6.1.2" pub_semver: dependency: transitive description: name: pub_semver - sha256: b5a5fcc6425ea43704852ba4453ba94b08c2226c63418a260240c3a054579014 + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.1.4" pubspec_parse: dependency: transitive description: name: pubspec_parse - sha256: "3686efe4a4613a4449b1a4ae08670aadbd3376f2e78d93e3f8f0919db02a7256" + sha256: c63b2876e58e194e4b0828fcb080ad0e06d051cb607a6be51a9e084f47cb9367 url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.2.3" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "81429e4481e1ccfb51ede496e916348668fd0921627779233bd24cc3ff6abd02" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "8568a389334b6e83415b6aae55378e158fbc2314e074983362d20c562780fb06" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "7708d83064f38060c7b39db12aefe449cb8cdc031d6062280087bc4cdb988f5c" + url: "https://pub.dev" + source: hosted + version: "2.3.5" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "9f2cbcf46d4270ea8be39fa156d86379077c8a5228d9dfdb1164ae0bb93f1faa" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "22e2ecac9419b4246d7c22bfbbda589e3acf5c0351137d87dd2939d984d37c3b" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: d762709c2bbe80626ecc819143013cc820fa49ca5e363620ee20a8b15a3e3daf + url: "https://pub.dev" + source: hosted + version: "2.2.1" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "841ad54f3c8381c480d0c9b508b89a34036f512482c407e6df7a9c4aa2ef8f59" + url: "https://pub.dev" + source: hosted + version: "2.3.2" shelf: dependency: transitive description: name: shelf - sha256: c240984c924796e055e831a0a36db23be8cb04f170b26df572931ab36418421d + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.4.1" shelf_web_socket: dependency: transitive description: name: shelf_web_socket - sha256: fd84910bf7d58db109082edf7326b75322b8f186162028482f53dc892f00332d + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.0.4" sky_engine: dependency: transitive description: flutter @@ -468,26 +609,26 @@ packages: dependency: transitive description: name: stack_trace - sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 url: "https://pub.dev" source: hosted - version: "1.11.1" + version: "1.11.0" stream_channel: dependency: transitive description: name: stream_channel - sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.1" stream_transform: dependency: transitive description: name: stream_transform - sha256: ed464977cb26a1f41537e177e190c67223dbd9f4f683489b6ab2e5d211ec564e + sha256: "14a00e794c7c11aa145a170587321aedce29769c08d7f58b1d141da75e3b1c6f" url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.1.0" string_scanner: dependency: transitive description: @@ -508,50 +649,50 @@ packages: dependency: transitive description: name: test_api - sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" url: "https://pub.dev" source: hosted - version: "0.6.1" + version: "0.6.0" timing: dependency: transitive description: name: timing - sha256: c386d07d7f5efc613479a7c4d9d64b03710b03cfaa7e8ad5f2bfb295a1f0dfad + sha256: "70a3b636575d4163c477e6de42f247a23b315ae20e86442bebe32d3cabf61c32" url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "1.0.1" typed_data: dependency: transitive description: name: typed_data - sha256: "53bdf7e979cfbf3e28987552fd72f637e63f3c8724c9e56d9246942dc2fa36ee" + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.3.2" vector_graphics: dependency: transitive description: name: vector_graphics - sha256: "18f6690295af52d081f6808f2f7c69f0eed6d7e23a71539d75f4aeb8f0062172" + sha256: "32c3c684e02f9bc0afb0ae0aa653337a2fe022e8ab064bcd7ffda27a74e288e3" url: "https://pub.dev" source: hosted - version: "1.1.9+2" + version: "1.1.11+1" vector_graphics_codec: dependency: transitive description: name: vector_graphics_codec - sha256: "531d20465c10dfac7f5cd90b60bbe4dd9921f1ec4ca54c83ebb176dbacb7bb2d" + sha256: c86987475f162fadff579e7320c7ddda04cd2fdeffbe1129227a85d9ac9e03da url: "https://pub.dev" source: hosted - version: "1.1.9+2" + version: "1.1.11+1" vector_graphics_compiler: dependency: transitive description: name: vector_graphics_compiler - sha256: "03012b0a33775c5530576b70240308080e1d5050f0faf000118c20e6463bc0ad" + sha256: "12faff3f73b1741a36ca7e31b292ddeb629af819ca9efe9953b70bd63fc8cd81" url: "https://pub.dev" source: hosted - version: "1.1.9+2" + version: "1.1.11+1" vector_math: dependency: transitive description: @@ -564,42 +705,58 @@ packages: dependency: transitive description: name: watcher - sha256: e42dfcc48f67618344da967b10f62de57e04bae01d9d3af4c2596f3712a88c99 + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.1.0" web: dependency: transitive description: name: web - sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152 + sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 url: "https://pub.dev" source: hosted - version: "0.3.0" + version: "0.1.4-beta" web_socket_channel: dependency: transitive description: name: web_socket_channel - sha256: "0c2ada1b1aeb2ad031ca81872add6be049b8cb479262c6ad3c4b0f9c24eaab2f" + sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.4.0" + win32: + dependency: transitive + description: + name: win32 + sha256: b0f37db61ba2f2e9b7a78a1caece0052564d1bc70668156cf3a29d676fe4e574 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d + url: "https://pub.dev" + source: hosted + version: "1.0.4" xml: dependency: transitive description: name: xml - sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226 + sha256: "5bc72e1e45e941d825fd7468b9b4cc3b9327942649aeb6fc5cdbf135f0a86e84" url: "https://pub.dev" source: hosted - version: "6.5.0" + version: "6.3.0" yaml: dependency: transitive description: name: yaml - sha256: "3cee79b1715110341012d27756d9bae38e650588acd38d3f3c610822e1337ace" + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" url: "https://pub.dev" source: hosted - version: "3.1.0" + version: "3.1.2" sdks: - dart: ">=3.2.0 <4.0.0" - flutter: ">=3.7.0-0" + dart: ">=3.1.0 <4.0.0" + flutter: ">=3.10.0" diff --git a/pubspec.yaml b/pubspec.yaml index be3055e0..23bb2d63 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,6 +16,9 @@ dependencies: dio: ^5.4.0 json_annotation: ^4.8.1 flutter_svg: ^2.0.9 + get_it: ^7.6.7 + provider: + shared_preferences: dev_dependencies: flutter_test: @@ -23,6 +26,7 @@ dev_dependencies: flutter_lints: ^1.0.2 build_runner: ^2.4.8 json_serializable: ^6.7.1 + mockito: flutter: uses-material-design: true diff --git a/test/presentation/restaurants/restaurant_list/restaurant_list_page_test.dart b/test/presentation/restaurants/restaurant_list/restaurant_list_page_test.dart new file mode 100644 index 00000000..b9f6c07e --- /dev/null +++ b/test/presentation/restaurants/restaurant_list/restaurant_list_page_test.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:restaurantour/dependency_injection/di_locator.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_page.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart'; +import 'package:restaurantour/presentation/utils/constants.dart'; + +import '../../../test_utils/mocks.mocks.dart'; + +void main() { + group('RestaurantListPage widget test', () { + final mockRestaurantListViewModel = MockRestaurantListViewModel(); + final mockGetRestaurantsUseCase = MockGetRestaurantsUseCase(); + final mockWatchFavoriteRestaurantsUseCase = + MockWatchFavoriteRestaurantsUseCase(); + + setUpAll(() { + testRegister(mockGetRestaurantsUseCase); + testRegister( + mockWatchFavoriteRestaurantsUseCase); + testRegister(mockRestaurantListViewModel); + }); + + tearDownAll(() { + locator.reset(); + }); + + testWidgets('should show CircularProgressIndicator when loading', + (WidgetTester tester) async { + when(mockRestaurantListViewModel.isLoading).thenReturn(true); + + await tester.pumpWidget( + const MaterialApp(home: RestaurantListPage()), + ); + + expect(find.byType(CircularProgressIndicator), findsOneWidget); + }); + + testWidgets('should show error message when has error', + (WidgetTester tester) async { + when(mockRestaurantListViewModel.isLoading).thenReturn(false); + when(mockRestaurantListViewModel.hasError).thenReturn(true); + + await tester.pumpWidget( + const MaterialApp(home: RestaurantListPage()), + ); + + expect(find.text(Constants.errorFetching), findsOneWidget); + }); + + testWidgets('should show ListView when has data', + (WidgetTester tester) async { + when(mockRestaurantListViewModel.isLoading).thenReturn(false); + when(mockRestaurantListViewModel.hasError).thenReturn(false); + when(mockRestaurantListViewModel.hasData).thenReturn(true); + when(mockRestaurantListViewModel.restaurants).thenReturn( + [ + const RestaurantEntity( + id: '1', + name: 'Restaurant 1', + rating: 4.5, + reviews: [], + isOpen: false, + price: '££', + heroImage: '', + category: 'Category', + address: 'Address', + ), + ], + ); + + await tester.pumpWidget( + const MaterialApp(home: RestaurantListPage()), + ); + + expect(find.byType(ListView), findsOneWidget); + }); + }); +} diff --git a/test/presentation/restaurants/restaurant_list/restaurant_list_view_model_test.dart b/test/presentation/restaurants/restaurant_list/restaurant_list_view_model_test.dart new file mode 100644 index 00000000..37fc24cd --- /dev/null +++ b/test/presentation/restaurants/restaurant_list/restaurant_list_view_model_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart'; + +import '../../../test_utils/mocks.mocks.dart'; + +void main() { + group('$RestaurantListViewModel', () { + late MockGetRestaurantsUseCase mockGetRestaurantsUseCase; + late MockWatchFavoriteRestaurantsUseCase + mockWatchFavoriteRestaurantsUseCase; + late RestaurantListViewModel viewModel; + setUp(() { + mockGetRestaurantsUseCase = MockGetRestaurantsUseCase(); + mockWatchFavoriteRestaurantsUseCase = + MockWatchFavoriteRestaurantsUseCase(); + viewModel = RestaurantListViewModel( + mockGetRestaurantsUseCase, + mockWatchFavoriteRestaurantsUseCase, + ); + when(mockGetRestaurantsUseCase(0)).thenAnswer( + (_) async => [ + const RestaurantEntity( + id: 'abc', + name: 'abc', + heroImage: 'heroImage', + price: 'price', + rating: 5.0, + category: 'category', + address: 'address', + isOpen: false, + reviews: [], + ), + ], + ); + }); + + test('init should get restaurants and listen to favorites', () async { + viewModel.init(); + + expect(viewModel.isLoading, true); + verify(mockGetRestaurantsUseCase(0)).called(1); + verify(mockWatchFavoriteRestaurantsUseCase()).called(1); + + await Future.delayed(Duration.zero); + expect(viewModel.isLoading, false); + expect(viewModel.hasData, true); + expect(viewModel.restaurants.length, 1); + }); + }); +} diff --git a/test/test_utils/mocks.dart b/test/test_utils/mocks.dart new file mode 100644 index 00000000..76d83092 --- /dev/null +++ b/test/test_utils/mocks.dart @@ -0,0 +1,15 @@ +import 'package:mockito/annotations.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart'; + +@GenerateNiceMocks( + [ + MockSpec(), + MockSpec(), + MockSpec(), + ], +) +void main() { + // ... +} diff --git a/test/test_utils/mocks.mocks.dart b/test/test_utils/mocks.mocks.dart new file mode 100644 index 00000000..c3fc6b71 --- /dev/null +++ b/test/test_utils/mocks.mocks.dart @@ -0,0 +1,168 @@ +// Mocks generated by Mockito 5.4.4 from annotations +// in restaurantour/test/test_utils/mocks.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; +import 'dart:ui' as _i7; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart' + as _i4; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart' + as _i2; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart' + as _i5; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart' + as _i6; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class + +/// A class which mocks [GetRestaurantsUseCase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockGetRestaurantsUseCase extends _i1.Mock + implements _i2.GetRestaurantsUseCase { + @override + _i3.Future> call(int? offset) => + (super.noSuchMethod( + Invocation.method( + #call, + [offset], + ), + returnValue: _i3.Future>.value( + <_i4.RestaurantEntity>[]), + returnValueForMissingStub: _i3.Future>.value( + <_i4.RestaurantEntity>[]), + ) as _i3.Future>); +} + +/// A class which mocks [WatchFavoriteRestaurantsUseCase]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWatchFavoriteRestaurantsUseCase extends _i1.Mock + implements _i5.WatchFavoriteRestaurantsUseCase { + @override + _i3.Stream> call() => (super.noSuchMethod( + Invocation.method( + #call, + [], + ), + returnValue: _i3.Stream>.empty(), + returnValueForMissingStub: _i3.Stream>.empty(), + ) as _i3.Stream>); +} + +/// A class which mocks [RestaurantListViewModel]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockRestaurantListViewModel extends _i1.Mock + implements _i6.RestaurantListViewModel { + @override + List<_i4.RestaurantEntity> get restaurants => (super.noSuchMethod( + Invocation.getter(#restaurants), + returnValue: <_i4.RestaurantEntity>[], + returnValueForMissingStub: <_i4.RestaurantEntity>[], + ) as List<_i4.RestaurantEntity>); + + @override + List get favoriteRestaurants => (super.noSuchMethod( + Invocation.getter(#favoriteRestaurants), + returnValue: [], + returnValueForMissingStub: [], + ) as List); + + @override + bool get hasError => (super.noSuchMethod( + Invocation.getter(#hasError), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); + + @override + bool get isLoading => (super.noSuchMethod( + Invocation.getter(#isLoading), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); + + @override + bool get hasData => (super.noSuchMethod( + Invocation.getter(#hasData), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); + + @override + bool get hasListeners => (super.noSuchMethod( + Invocation.getter(#hasListeners), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); + + @override + void init() => super.noSuchMethod( + Invocation.method( + #init, + [], + ), + returnValueForMissingStub: null, + ); + + @override + void dispose() => super.noSuchMethod( + Invocation.method( + #dispose, + [], + ), + returnValueForMissingStub: null, + ); + + @override + _i3.Future getRestaurants() => (super.noSuchMethod( + Invocation.method( + #getRestaurants, + [], + ), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + void addListener(_i7.VoidCallback? listener) => super.noSuchMethod( + Invocation.method( + #addListener, + [listener], + ), + returnValueForMissingStub: null, + ); + + @override + void removeListener(_i7.VoidCallback? listener) => super.noSuchMethod( + Invocation.method( + #removeListener, + [listener], + ), + returnValueForMissingStub: null, + ); + + @override + void notifyListeners() => super.noSuchMethod( + Invocation.method( + #notifyListeners, + [], + ), + returnValueForMissingStub: null, + ); +}