From 96516110dba1b870b56cb6f888501d04bce69b49 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 11:26:16 -0500 Subject: [PATCH 01/16] feat(setup): initial repo and api setup --- .fvm/fvm_config.json | 3 +-- .fvmrc | 3 +++ .gitignore | 4 +++- .vscode/settings.json | 14 +++++------ lib/repositories/yelp_repository.dart | 5 ++-- pubspec.lock | 34 +++++++++++++-------------- 6 files changed, 34 insertions(+), 29 deletions(-) create mode 100644 .fvmrc 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..2951c6d3 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/versions/3.13.9", + "search.exclude": { + "**/.fvm": true + }, + "files.watcherExclude": { + "**/.fvm": true + } } \ No newline at end of file diff --git a/lib/repositories/yelp_repository.dart b/lib/repositories/yelp_repository.dart index f251d7b4..5554a424 100644 --- a/lib/repositories/yelp_repository.dart +++ b/lib/repositories/yelp_repository.dart @@ -2,7 +2,8 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:restaurantour/models/restaurant.dart'; -const _apiKey = ''; +const _apiKey = + 'wfYIpeyetAPJbQYg5ITUE4wxzqCvoEQM5FQyW9Xq4SGJG52vkefWY_Irq9yg_TKpXRYJUgTO48W_fVXReEABY919sT74bHoCAyNH4b0kTe94rmEWFWNo1GjFxUXjZXYx'; class YelpRepository { late Dio dio; @@ -73,7 +74,7 @@ class YelpRepository { String _getQuery(int offset) { return ''' query getRestaurants { - search(location: "Las Vegas", limit: 20, offset: $offset) { + search(location: "Las Vegas", limit: 1, offset: $offset) { total business { id diff --git a/pubspec.lock b/pubspec.lock index 0b052c68..6e7a1f3d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -149,10 +149,10 @@ 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: @@ -351,10 +351,10 @@ 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: @@ -391,10 +391,10 @@ packages: dependency: transitive description: name: petitparser - sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27 + sha256: cb3798bef7fc021ac45b308f4b51208a152792445cce0448c9a4ba5879dd8750 url: "https://pub.dev" source: hosted - version: "6.0.2" + version: "5.4.0" pool: dependency: transitive description: @@ -468,18 +468,18 @@ 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: @@ -508,10 +508,10 @@ 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: @@ -572,10 +572,10 @@ packages: 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: @@ -588,10 +588,10 @@ packages: 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: @@ -601,5 +601,5 @@ packages: source: hosted version: "3.1.0" sdks: - dart: ">=3.2.0 <4.0.0" + dart: ">=3.1.0-185.0.dev <4.0.0" flutter: ">=3.7.0-0" From 25de54b3e91916a4355802af608f277bf2a39d0b Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 11:38:41 -0500 Subject: [PATCH 02/16] feat(restaurant-list): restaurant list pageand listTile --- .vscode/settings.json | 2 +- lib/design_system/restaurant_list_tile.dart | 79 +++++++++++++++++++++ lib/main.dart | 3 +- lib/view/restaurant_list_page.dart | 28 ++++++++ 4 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 lib/design_system/restaurant_list_tile.dart create mode 100644 lib/view/restaurant_list_page.dart diff --git a/.vscode/settings.json b/.vscode/settings.json index 2951c6d3..0e6ea20d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,5 @@ { - "dart.flutterSdkPath": ".fvm/versions/3.13.9", + "dart.flutterSdkPath": ".fvm/flutter_sdk", "search.exclude": { "**/.fvm": true }, diff --git a/lib/design_system/restaurant_list_tile.dart b/lib/design_system/restaurant_list_tile.dart new file mode 100644 index 00000000..feea2ef5 --- /dev/null +++ b/lib/design_system/restaurant_list_tile.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; + +class RestaurantListTile extends StatelessWidget { + final String imageUrl; + final String name; + final String priceRange; + final double rating; + final bool isOpen; + + const RestaurantListTile({ + Key? key, + required this.imageUrl, + required this.name, + required this.priceRange, + required this.rating, + required this.isOpen, + }) : super(key: key); + + @override + Widget build(BuildContext context) { + return ListTile( + leading: Image.network( + imageUrl, + width: 70, + height: 70, + fit: BoxFit.cover, + ), + title: Text(name), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(priceRange), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _StarRating(rating: rating), + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isOpen ? Colors.green : Colors.red, + ), + ), + ], + ), + ], + ), + ); + } +} + +class _StarRating extends StatelessWidget { + final double rating; + + const _StarRating({ + Key? key, + required this.rating, + }) : super(key: key); + + @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/main.dart b/lib/main.dart index c6ce7473..89b91662 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:restaurantour/repositories/yelp_repository.dart'; +import 'package:restaurantour/view/restaurant_list_page.dart'; void main() { runApp(const Restaurantour()); @@ -16,7 +17,7 @@ class Restaurantour extends StatelessWidget { theme: ThemeData( visualDensity: VisualDensity.adaptivePlatformDensity, ), - home: const HomePage(), + home: const RestaurantListPage(), ); } } diff --git a/lib/view/restaurant_list_page.dart b/lib/view/restaurant_list_page.dart new file mode 100644 index 00000000..f1fd0746 --- /dev/null +++ b/lib/view/restaurant_list_page.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; +import 'package:restaurantour/design_system/restaurant_list_tile.dart'; + +class RestaurantListPage extends StatelessWidget { + const RestaurantListPage({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Restaurant List'), + ), + body: ListView.builder( + itemCount: 1, + itemBuilder: (context, index) { + return const RestaurantListTile( + imageUrl: + 'https:///s3-media4.fl.yelpcdn.com/bphoto/_zXRdYX4r1OBfF86xKMbDw/o.jpg', + name: 'Sample Restaurant', + priceRange: '2', + rating: 4.5, + isOpen: false, + ); + }, + ), + ); + } +} From 00677ff4c3d6156044444e4403052e57c5eafb77 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 15:23:16 -0500 Subject: [PATCH 03/16] feat(DI): dependency injection, basic structure --- ios/Flutter/Debug.xcconfig | 1 + ios/Flutter/Release.xcconfig | 1 + ios/Podfile | 44 +++++ ios/Podfile.lock | 23 +++ ios/Runner.xcodeproj/project.pbxproj | 68 ++++++++ .../contents.xcworkspacedata | 3 + .../repositories/yelp_repository.dart | 0 lib/di_locator.dart | 21 +++ .../entities/restaurant_entity.dart | 40 +++++ .../repositories/restaurant_repository.dart | 5 + .../use_cases/get_restaurants_use_case.dart | 12 ++ lib/main.dart | 50 ++---- .../restaurant_list_page.dart | 0 .../restaurant_list_view_model.dart | 55 +++++++ pubspec.lock | 153 +++++++++++++++++- pubspec.yaml | 3 + 16 files changed, 440 insertions(+), 39 deletions(-) create mode 100644 ios/Podfile create mode 100644 ios/Podfile.lock rename lib/{ => data/network}/repositories/yelp_repository.dart (100%) create mode 100644 lib/di_locator.dart create mode 100644 lib/domain/restaurants/entities/restaurant_entity.dart create mode 100644 lib/domain/restaurants/repositories/restaurant_repository.dart create mode 100644 lib/domain/restaurants/use_cases/get_restaurants_use_case.dart rename lib/view/{ => restaurants}/restaurant_list_page.dart (100%) create mode 100644 lib/view/restaurants/restaurant_list_view_model.dart 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..3c6dbb6d --- /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..c454fc37 --- /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: aa3b1d9cb94e8055dc6468141196cf9e4c8e33df + +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/repositories/yelp_repository.dart b/lib/data/network/repositories/yelp_repository.dart similarity index 100% rename from lib/repositories/yelp_repository.dart rename to lib/data/network/repositories/yelp_repository.dart diff --git a/lib/di_locator.dart b/lib/di_locator.dart new file mode 100644 index 00000000..fb46b12d --- /dev/null +++ b/lib/di_locator.dart @@ -0,0 +1,21 @@ +import 'package:get_it/get_it.dart'; +import 'package:restaurantour/data/network/repositories/yelp_repository.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list_view_model.dart'; + +final locator = GetIt.instance; + +void setupLocator() { + // Use cases + locator.registerFactory( + () => GetRestaurantsUseCase(locator()), + ); + + // Repositories + locator.registerLazySingleton(() => YelpRepository()); + + // View Models + locator.registerLazySingleton( + () => RestaurantListViewModel(locator()), + ); +} diff --git a/lib/domain/restaurants/entities/restaurant_entity.dart b/lib/domain/restaurants/entities/restaurant_entity.dart new file mode 100644 index 00000000..784c3769 --- /dev/null +++ b/lib/domain/restaurants/entities/restaurant_entity.dart @@ -0,0 +1,40 @@ +class RestaurantEntity { + final String id; + final String name; + final String heroImage; + final String price; + final double rating; + final bool isOpen; + + const RestaurantEntity({ + required this.id, + required this.name, + required this.heroImage, + required this.price, + required this.rating, + required this.isOpen, + }); + + @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.isOpen == isOpen; + } + + @override + int get hashCode { + return id.hashCode ^ + name.hashCode ^ + heroImage.hashCode ^ + price.hashCode ^ + rating.hashCode ^ + isOpen.hashCode; + } +} diff --git a/lib/domain/restaurants/repositories/restaurant_repository.dart b/lib/domain/restaurants/repositories/restaurant_repository.dart new file mode 100644 index 00000000..00b94bbc --- /dev/null +++ b/lib/domain/restaurants/repositories/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/use_cases/get_restaurants_use_case.dart b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart new file mode 100644 index 00000000..f629a701 --- /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/restaurant_repository.dart'; + +class GetRestaurantsUseCase { + final RestaurantsRepository _restaurantsRepository; + + GetRestaurantsUseCase(this._restaurantsRepository); + + Future> call(int? offset) { + return _restaurantsRepository.getRestaurants(offset ?? 0); + } +} diff --git a/lib/main.dart b/lib/main.dart index 89b91662..c5dac167 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:restaurantour/repositories/yelp_repository.dart'; -import 'package:restaurantour/view/restaurant_list_page.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list_page.dart'; void main() { runApp(const Restaurantour()); @@ -14,45 +13,22 @@ class Restaurantour extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'RestauranTour', + debugShowCheckedModeBanner: false, theme: ThemeData( visualDensity: VisualDensity.adaptivePlatformDensity, - ), - home: const RestaurantListPage(), - ); - } -} - -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/view/restaurant_list_page.dart b/lib/view/restaurants/restaurant_list_page.dart similarity index 100% rename from lib/view/restaurant_list_page.dart rename to lib/view/restaurants/restaurant_list_page.dart diff --git a/lib/view/restaurants/restaurant_list_view_model.dart b/lib/view/restaurants/restaurant_list_view_model.dart new file mode 100644 index 00000000..7dcca6be --- /dev/null +++ b/lib/view/restaurants/restaurant_list_view_model.dart @@ -0,0 +1,55 @@ +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'; + +enum RestaurantListState { + loading, + loadingMore, + loaded, + error, +} + +class RestaurantListViewModel extends ChangeNotifier { + final GetRestaurantsUseCase _getRestaurantsUseCase; + + RestaurantListViewModel( + this._getRestaurantsUseCase, + ); + + 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; + + void init() { + fetchRestaurants(); + } + + Future?> fetchRestaurants() async { + try { + if (_state == RestaurantListState.loadingMore) return _restaurants; + print('fetching restaurants'); + + final result = await _getRestaurantsUseCase(_offset); + _restaurants.addAll(result); + _offset += result.length; + _state = RestaurantListState.loaded; + notifyListeners(); + return result; + } catch (e) { + _state = RestaurantListState.error; + notifyListeners(); + return null; + } + } +} diff --git a/pubspec.lock b/pubspec.lock index 6e7a1f3d..17d37e83 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -201,6 +201,14 @@ 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: @@ -243,6 +251,11 @@ packages: 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,6 +264,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.0" + get_it: + dependency: "direct dev" + description: + name: get_it + sha256: e6017ce7fdeaf218dc51a100344d8cb70134b80e28b760f8bb23c242437bafd7 + url: "https://pub.dev" + source: hosted + version: "7.6.7" glob: dependency: transitive description: @@ -363,6 +384,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.1" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" package_config: dependency: transitive description: @@ -387,6 +416,30 @@ 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: @@ -395,6 +448,22 @@ packages: 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: "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: @@ -403,6 +472,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.0" + provider: + dependency: "direct dev" + description: + name: provider + sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c + url: "https://pub.dev" + source: hosted + version: "6.1.2" pub_semver: dependency: transitive description: @@ -419,6 +496,62 @@ packages: url: "https://pub.dev" source: hosted version: "1.2.0" + shared_preferences: + dependency: "direct dev" + 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: @@ -584,6 +717,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.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: @@ -601,5 +750,5 @@ packages: source: hosted version: "3.1.0" sdks: - dart: ">=3.1.0-185.0.dev <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..cbe4bf92 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -23,6 +23,9 @@ dev_dependencies: flutter_lints: ^1.0.2 build_runner: ^2.4.8 json_serializable: ^6.7.1 + get_it: ^7.6.7 + provider: + shared_preferences: flutter: uses-material-design: true From db27b66e7277cc95324b1dd33b7b332e10194ef5 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 17:32:27 -0500 Subject: [PATCH 04/16] chore(use-cases): use case implementation --- .../use_cases/get_restaurants_use_case.dart | 2 +- .../save_favorite_restaurant_use_case.dart | 14 ++++++++++++++ .../watch_favorite_restaurants_use_case.dart | 13 +++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart create mode 100644 lib/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart diff --git a/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart index f629a701..e2526332 100644 --- a/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart +++ b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart @@ -1,5 +1,5 @@ import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; -import 'package:restaurantour/domain/restaurants/repositories/restaurant_repository.dart'; +import 'package:restaurantour/domain/restaurants/repository_interfaces/restaurant_repository.dart'; class GetRestaurantsUseCase { final RestaurantsRepository _restaurantsRepository; diff --git a/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart b/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart new file mode 100644 index 00000000..45830e51 --- /dev/null +++ b/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart @@ -0,0 +1,14 @@ +import 'package:restaurantour/domain/restaurants/repository_interfaces/preferences_repository.dart'; + +class SaveFavoriteRestaurantUseCase { + final PreferencesRepository _preferencesRepository; + + SaveFavoriteRestaurantUseCase(this._preferencesRepository); + + Future call(String restaurantId) async { + await _preferencesRepository.addFavoriteRestaurant(restaurantId); + final currentFavorites = + await _preferencesRepository.getFavoriteRestaurants(); + print('Current favorites: $currentFavorites'); + } +} 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..b1380e9b --- /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/repository_interfaces/preferences_repository.dart'; + +class WatchFavoriteRestaurantsUseCase { + final PreferencesRepository _preferencesRepository; + + WatchFavoriteRestaurantsUseCase(this._preferencesRepository); + + Stream> call() { + return _preferencesRepository.watchFavoriteRestaurants(); + } +} From 96cfbbdc489ce8a12737937e26d0079c08c2ca1e Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 17:34:27 -0500 Subject: [PATCH 05/16] chore(repositories): shared preferences, restaurants repo --- lib/{ => data}/models/restaurant.dart | 2 + lib/{ => data}/models/restaurant.g.dart | 2 + .../shared_preferences_repository.dart | 41 +++++++++++++++ .../network/repositories/yelp_repository.dart | 50 ++++++++++++++++--- lib/data/restaurant_mapper.dart | 26 ++++++++++ .../preferences_repository.dart | 5 ++ .../restaurant_repository.dart | 5 ++ 7 files changed, 125 insertions(+), 6 deletions(-) rename lib/{ => data}/models/restaurant.dart (98%) rename lib/{ => data}/models/restaurant.g.dart (98%) create mode 100644 lib/data/network/repositories/shared_preferences_repository.dart create mode 100644 lib/data/restaurant_mapper.dart create mode 100644 lib/domain/restaurants/repository_interfaces/preferences_repository.dart create mode 100644 lib/domain/restaurants/repository_interfaces/restaurant_repository.dart 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/network/repositories/shared_preferences_repository.dart b/lib/data/network/repositories/shared_preferences_repository.dart new file mode 100644 index 00000000..d5231ba3 --- /dev/null +++ b/lib/data/network/repositories/shared_preferences_repository.dart @@ -0,0 +1,41 @@ +import 'dart:async'; + +import 'package:restaurantour/domain/restaurants/repository_interfaces/preferences_repository.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// A [PreferencesRepository] implementation that uses [SharedPreferences] as the +/// underlying storage. +/// +/// Should be replaced with a more robust solution in a production environment. + +class SharedPreferencesRepository extends PreferencesRepository { + 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 addFavoriteRestaurant(String restaurantId) async { + final prefs = await SharedPreferences.getInstance(); + final favorites = prefs.getStringList(_key) ?? []; + if (!favorites.contains(restaurantId)) { + favorites.add(restaurantId); + await prefs.setStringList(_key, favorites); + } + } + + @override + Stream> watchFavoriteRestaurants() { + return _controller.stream; + } + + void dispose() { + _controller.close(); + } +} diff --git a/lib/data/network/repositories/yelp_repository.dart b/lib/data/network/repositories/yelp_repository.dart index 5554a424..35a7e503 100644 --- a/lib/data/network/repositories/yelp_repository.dart +++ b/lib/data/network/repositories/yelp_repository.dart @@ -1,11 +1,16 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; -import 'package:restaurantour/models/restaurant.dart'; +import 'package:restaurantour/data/exceptions/mapper_exception.dart'; +import 'package:restaurantour/data/exceptions/network_exception.dart'; +import 'package:restaurantour/data/models/restaurant.dart'; +import 'package:restaurantour/data/restaurant_mapper.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/repository_interfaces/restaurant_repository.dart'; const _apiKey = 'wfYIpeyetAPJbQYg5ITUE4wxzqCvoEQM5FQyW9Xq4SGJG52vkefWY_Irq9yg_TKpXRYJUgTO48W_fVXReEABY919sT74bHoCAyNH4b0kTe94rmEWFWNo1GjFxUXjZXYx'; -class YelpRepository { +class YelpRepository extends RestaurantsRepository { late Dio dio; YelpRepository({ @@ -30,7 +35,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" @@ -59,16 +64,27 @@ class YelpRepository { /// } /// } /// - Future getRestaurants({int offset = 0}) async { + + Future?> getRestaurantsFromApi({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) { @@ -85,6 +101,7 @@ query getRestaurants { reviews { id rating + text user { id image_url @@ -106,4 +123,25 @@ query getRestaurants { } '''; } + + @override + Future> getRestaurants(int offset) async { + if (offset != 0) { + //wont call api to prevent exceeding limit + print('calling api with offset: $offset'); + return Future.value([]); + } + final result = await getRestaurantsFromApi(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/data/restaurant_mapper.dart b/lib/data/restaurant_mapper.dart new file mode 100644 index 00000000..0124d418 --- /dev/null +++ b/lib/data/restaurant_mapper.dart @@ -0,0 +1,26 @@ +import 'package:restaurantour/data/exceptions/mapper_exception.dart'; +import 'package:restaurantour/data/models/restaurant.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_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'); + } + return RestaurantEntity( + id: model.id ?? '', + name: model.name ?? '', + price: model.price ?? '', + rating: model.rating ?? 0.0, + heroImage: model.photos?.first ?? '', + isOpen: model.isOpen, + ); + } + + // 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/repository_interfaces/preferences_repository.dart b/lib/domain/restaurants/repository_interfaces/preferences_repository.dart new file mode 100644 index 00000000..860303b0 --- /dev/null +++ b/lib/domain/restaurants/repository_interfaces/preferences_repository.dart @@ -0,0 +1,5 @@ +abstract class PreferencesRepository { + Future addFavoriteRestaurant(String restaurantId); + Future> getFavoriteRestaurants(); + Stream> watchFavoriteRestaurants(); +} diff --git a/lib/domain/restaurants/repository_interfaces/restaurant_repository.dart b/lib/domain/restaurants/repository_interfaces/restaurant_repository.dart new file mode 100644 index 00000000..00b94bbc --- /dev/null +++ b/lib/domain/restaurants/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); +} From b3aadb4de59984be4d8a87ba7791af833812923f Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 17:35:44 -0500 Subject: [PATCH 06/16] feat(restaurant-detail): restaurant detail page --- lib/data/exceptions/mapper_exception.dart | 10 +++++ lib/data/exceptions/network_exception.dart | 10 +++++ lib/dependency_injection/di_locator.dart | 43 +++++++++++++++++++ lib/di_locator.dart | 21 --------- .../repositories/restaurant_repository.dart | 5 --- lib/main.dart | 2 + .../restaurant_list_view_model.dart | 28 +++++++++++- 7 files changed, 91 insertions(+), 28 deletions(-) create mode 100644 lib/data/exceptions/mapper_exception.dart create mode 100644 lib/data/exceptions/network_exception.dart create mode 100644 lib/dependency_injection/di_locator.dart delete mode 100644 lib/di_locator.dart delete mode 100644 lib/domain/restaurants/repositories/restaurant_repository.dart diff --git a/lib/data/exceptions/mapper_exception.dart b/lib/data/exceptions/mapper_exception.dart new file mode 100644 index 00000000..3db59fc0 --- /dev/null +++ b/lib/data/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/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/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart new file mode 100644 index 00000000..a8ca80c6 --- /dev/null +++ b/lib/dependency_injection/di_locator.dart @@ -0,0 +1,43 @@ +import 'package:get_it/get_it.dart'; +import 'package:restaurantour/data/network/repositories/shared_preferences_repository.dart'; +import 'package:restaurantour/data/network/repositories/yelp_repository.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list_view_model.dart'; + +final locator = GetIt.instance; + +void setupLocator() { + // UseCases + locator.registerFactory( + () => GetRestaurantsUseCase( + locator(), + ), + ); + locator.registerFactory( + () => SaveFavoriteRestaurantUseCase( + locator(), + ), + ); + locator.registerFactory( + () => WatchFavoriteRestaurantsUseCase( + locator(), + ), + ); + + // Repositories + locator.registerLazySingleton(() => YelpRepository()); + locator.registerLazySingleton( + () => SharedPreferencesRepository(), + ); + + // ViewModels + locator.registerLazySingleton( + () => RestaurantListViewModel( + locator(), + locator(), + locator(), + ), + ); +} diff --git a/lib/di_locator.dart b/lib/di_locator.dart deleted file mode 100644 index fb46b12d..00000000 --- a/lib/di_locator.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:get_it/get_it.dart'; -import 'package:restaurantour/data/network/repositories/yelp_repository.dart'; -import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list_view_model.dart'; - -final locator = GetIt.instance; - -void setupLocator() { - // Use cases - locator.registerFactory( - () => GetRestaurantsUseCase(locator()), - ); - - // Repositories - locator.registerLazySingleton(() => YelpRepository()); - - // View Models - locator.registerLazySingleton( - () => RestaurantListViewModel(locator()), - ); -} diff --git a/lib/domain/restaurants/repositories/restaurant_repository.dart b/lib/domain/restaurants/repositories/restaurant_repository.dart deleted file mode 100644 index 00b94bbc..00000000 --- a/lib/domain/restaurants/repositories/restaurant_repository.dart +++ /dev/null @@ -1,5 +0,0 @@ -import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; - -abstract class RestaurantsRepository { - Future> getRestaurants(int offset); -} diff --git a/lib/main.dart b/lib/main.dart index c5dac167..190dd43c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:restaurantour/dependency_injection/di_locator.dart'; import 'package:restaurantour/view/restaurants/restaurant_list_page.dart'; void main() { + setupLocator(); runApp(const Restaurantour()); } diff --git a/lib/view/restaurants/restaurant_list_view_model.dart b/lib/view/restaurants/restaurant_list_view_model.dart index 7dcca6be..6ef66119 100644 --- a/lib/view/restaurants/restaurant_list_view_model.dart +++ b/lib/view/restaurants/restaurant_list_view_model.dart @@ -3,6 +3,8 @@ 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/save_favorite_restaurant_use_case.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; enum RestaurantListState { loading, @@ -13,9 +15,13 @@ enum RestaurantListState { class RestaurantListViewModel extends ChangeNotifier { final GetRestaurantsUseCase _getRestaurantsUseCase; + final SaveFavoriteRestaurantUseCase _saveFavoriteRestaurantUseCase; + final WatchFavoriteRestaurantsUseCase _watchFavoriteRestaurantsUseCase; RestaurantListViewModel( this._getRestaurantsUseCase, + this._saveFavoriteRestaurantUseCase, + this._watchFavoriteRestaurantsUseCase, ); final List _restaurants = []; @@ -31,11 +37,25 @@ class RestaurantListViewModel extends ChangeNotifier { int _offset = 0; + StreamSubscription>? _favoritesSubscription; + void init() { - fetchRestaurants(); + getRestaurants(); + _favoritesSubscription?.cancel(); + _favoritesSubscription = _watchFavoriteRestaurantsUseCase().listen((event) { + _favoriteRestaurants?.add(event as String); + print('favorites: $_favoriteRestaurants'); + notifyListeners(); + }); + } + + @override + void dispose() { + super.dispose(); + _favoritesSubscription?.cancel(); } - Future?> fetchRestaurants() async { + Future?> getRestaurants() async { try { if (_state == RestaurantListState.loadingMore) return _restaurants; print('fetching restaurants'); @@ -52,4 +72,8 @@ class RestaurantListViewModel extends ChangeNotifier { return null; } } + + Future saveFavorite(String restaurantId) async { + await _saveFavoriteRestaurantUseCase(restaurantId); + } } From 90441245bb476b0c6fcd109ec0b20366fa6a24bf Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 17:36:11 -0500 Subject: [PATCH 07/16] build: upgrade dependencies --- ios/Podfile | 2 +- pubspec.lock | 168 +++++++++++++++++++++++++-------------------------- 2 files changed, 85 insertions(+), 85 deletions(-) diff --git a/ios/Podfile b/ios/Podfile index 3c6dbb6d..ba7f94f9 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -# platform :ios, '11.0' +platform :ios, '11.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/pubspec.lock b/pubspec.lock index 17d37e83..17e5d2e8 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: @@ -157,18 +149,18 @@ packages: 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: @@ -213,18 +205,18 @@ packages: 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 @@ -242,10 +234,10 @@ 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 @@ -276,10 +268,10 @@ packages: 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: @@ -288,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: @@ -348,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: @@ -380,10 +380,10 @@ packages: dependency: transitive description: name: mime - sha256: fd5f81041e6a9fc9b9d7fa2cb8a01123f9f5d5d49136e06cb9dc7d33689529f4 + sha256: e4ff8e8564c03f255408decd16e7899da1733852a9110a58fe6d1b817684a63e url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.0.4" nested: dependency: transitive description: @@ -396,10 +396,10 @@ packages: 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: @@ -468,10 +468,10 @@ packages: 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 dev" description: @@ -484,18 +484,18 @@ packages: 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 dev" description: @@ -556,18 +556,18 @@ packages: 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 @@ -617,10 +617,10 @@ packages: 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: @@ -649,42 +649,42 @@ packages: 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: @@ -697,10 +697,10 @@ 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: @@ -713,10 +713,10 @@ packages: 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: @@ -745,10 +745,10 @@ packages: 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.1.0 <4.0.0" flutter: ">=3.10.0" From a11562e0cdef29b28546e036642be7a35721d69a Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 17:42:01 -0500 Subject: [PATCH 08/16] feat(restaurant-detail): show restaurant detail page --- lib/design_system/restaurant_list_tile.dart | 57 ++++--- lib/main.dart | 1 - .../restaurants/restaurant_detail_page.dart | 72 ++++++++ .../restaurants/restaurant_list_page.dart | 157 ++++++++++++++++-- 4 files changed, 248 insertions(+), 39 deletions(-) create mode 100644 lib/view/restaurants/restaurant_detail_page.dart diff --git a/lib/design_system/restaurant_list_tile.dart b/lib/design_system/restaurant_list_tile.dart index feea2ef5..70c87956 100644 --- a/lib/design_system/restaurant_list_tile.dart +++ b/lib/design_system/restaurant_list_tile.dart @@ -6,6 +6,7 @@ class RestaurantListTile extends StatelessWidget { final String priceRange; final double rating; final bool isOpen; + final VoidCallback? onTap; const RestaurantListTile({ Key? key, @@ -14,37 +15,41 @@ class RestaurantListTile extends StatelessWidget { required this.priceRange, required this.rating, required this.isOpen, + this.onTap, }) : super(key: key); @override Widget build(BuildContext context) { - return ListTile( - leading: Image.network( - imageUrl, - width: 70, - height: 70, - fit: BoxFit.cover, - ), - title: Text(name), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(priceRange), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - _StarRating(rating: rating), - Container( - width: 10, - height: 10, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: isOpen ? Colors.green : Colors.red, + return GestureDetector( + onTap: onTap, + child: ListTile( + leading: Image.network( + imageUrl, + width: 70, + height: 70, + fit: BoxFit.cover, + ), + title: Text(name), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(priceRange), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _StarRating(rating: rating), + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isOpen ? Colors.green : Colors.red, + ), ), - ), - ], - ), - ], + ], + ), + ], + ), ), ); } diff --git a/lib/main.dart b/lib/main.dart index 190dd43c..07c94448 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -8,7 +8,6 @@ void main() { } class Restaurantour extends StatelessWidget { - // This widget is the root of your application. const Restaurantour({Key? key}) : super(key: key); @override diff --git a/lib/view/restaurants/restaurant_detail_page.dart b/lib/view/restaurants/restaurant_detail_page.dart new file mode 100644 index 00000000..05cfa501 --- /dev/null +++ b/lib/view/restaurants/restaurant_detail_page.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; + +class RestaurantDetailPage extends StatelessWidget { + const RestaurantDetailPage({ + Key? key, + required this.restaurant, + }) : super(key: key); + final RestaurantEntity restaurant; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Restaurant Detail'), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + // Navigate back to the previous page + Navigator.pop(context); + }, + ), + ), + body: Column( + children: [ + Image.network( + restaurant.heroImage, + fit: BoxFit.cover, + height: 200, + width: double.infinity, + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + restaurant.name, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + Text( + restaurant.price, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w500, + ), + ), + Text( + 'Rating: ${restaurant.rating}', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w500, + ), + ), + Text( + 'Open: ${restaurant.isOpen}', + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/view/restaurants/restaurant_list_page.dart b/lib/view/restaurants/restaurant_list_page.dart index f1fd0746..d8ce19ac 100644 --- a/lib/view/restaurants/restaurant_list_page.dart +++ b/lib/view/restaurants/restaurant_list_page.dart @@ -1,4 +1,9 @@ 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/view/restaurants/restaurant_detail_page.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list_view_model.dart'; import 'package:restaurantour/design_system/restaurant_list_tile.dart'; class RestaurantListPage extends StatelessWidget { @@ -6,23 +11,151 @@ class RestaurantListPage extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: const Text('Restaurant List'), + return DefaultTabController( + length: 2, + child: Scaffold( + appBar: AppBar( + title: const Text('Restaurant List'), + bottom: const TabBar( + labelStyle: TextStyle( + fontFamily: 'OpenSans', + fontSize: 14, + ), + labelColor: Colors.black, + tabs: [ + Tab( + text: 'All Restaurants', + ), + Tab( + text: 'My Favorites', + ), + ], + ), + ), + body: ChangeNotifierProvider( + create: (context) => locator()..init(), + builder: (context, child) { + return Consumer( + builder: (context, viewModel, child) { + return const TabBarView( + children: [ + _AllRestaurantsTab(), + _MyFavoritesTab(), + ], + ); + }, + ); + }, + ), ), - body: ListView.builder( - itemCount: 1, + ); + } +} + +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( + 'Oops, unable to fetch restaurants. Try again later.', + ), + ); + } + 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) { - return const RestaurantListTile( - imageUrl: - 'https:///s3-media4.fl.yelpcdn.com/bphoto/_zXRdYX4r1OBfF86xKMbDw/o.jpg', - name: 'Sample Restaurant', - priceRange: '2', - rating: 4.5, - isOpen: false, + 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, ); }, ), ); } } + +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( + 'Oops, unable to fetch restaurants. Try again later.', + ), + ); + } + + // display favorite restaurants + final favoriteRestaurants = viewModel.favoriteRestaurants; + + if (favoriteRestaurants.isEmpty) { + return const Center( + child: Text( + 'You have no favorite restaurants yet.', + ), + ); + } + return ListView.builder( + itemCount: favoriteRestaurants.length, + itemBuilder: (context, index) { + final restaurantId = favoriteRestaurants[index]; + final restaurant = viewModel.restaurants.firstWhere( + (element) => element.id == restaurantId, + ); + return RestaurantListTile( + imageUrl: restaurant.heroImage, + name: restaurant.name, + priceRange: restaurant.price, + rating: restaurant.rating, + isOpen: restaurant.isOpen, + ); + }, + ); + } +} From a94aebe8429f39ff233ed413752b34d131510c3c Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 17:42:59 -0500 Subject: [PATCH 09/16] build: podfile checksum --- ios/Podfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Podfile.lock b/ios/Podfile.lock index c454fc37..6f56688f 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -18,6 +18,6 @@ SPEC CHECKSUMS: Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 shared_preferences_foundation: b4c3b4cddf1c21f02770737f147a3f5da9d39695 -PODFILE CHECKSUM: aa3b1d9cb94e8055dc6468141196cf9e4c8e33df +PODFILE CHECKSUM: f567b6369f8842e77ccf6611a4baf3e2181f3f05 COCOAPODS: 1.15.2 From 379d2cd427db784cb7ea231cb74c460c150bce5b Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 18:13:46 -0500 Subject: [PATCH 10/16] chore(restaurant-detail): layout, reviews, models, etc --- lib/data/restaurant_mapper.dart | 21 ++++ lib/dependency_injection/di_locator.dart | 2 +- .../entities/restaurant_entity.dart | 10 +- .../restaurants/entities/review_entity.dart | 38 +++++++ .../restaurants/entities/user_entity.dart | 26 +++++ lib/main.dart | 2 +- .../restaurant_detail_page.dart | 102 ++++++++++++++++++ .../restaurants/restaurant_detail_page.dart | 72 ------------- .../restaurant_list_page.dart | 4 +- .../restaurant_list_view_model.dart | 0 10 files changed, 199 insertions(+), 78 deletions(-) create mode 100644 lib/domain/restaurants/entities/review_entity.dart create mode 100644 lib/domain/restaurants/entities/user_entity.dart create mode 100644 lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart delete mode 100644 lib/view/restaurants/restaurant_detail_page.dart rename lib/view/restaurants/{ => restaurant_list}/restaurant_list_page.dart (97%) rename lib/view/restaurants/{ => restaurant_list}/restaurant_list_view_model.dart (100%) diff --git a/lib/data/restaurant_mapper.dart b/lib/data/restaurant_mapper.dart index 0124d418..20ae0b4d 100644 --- a/lib/data/restaurant_mapper.dart +++ b/lib/data/restaurant_mapper.dart @@ -1,6 +1,8 @@ import 'package:restaurantour/data/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 { @@ -9,6 +11,24 @@ class RestaurantMapper { 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 ?? '', + ), + ), + ) + .toList() ?? + []; + return RestaurantEntity( id: model.id ?? '', name: model.name ?? '', @@ -16,6 +36,7 @@ class RestaurantMapper { rating: model.rating ?? 0.0, heroImage: model.photos?.first ?? '', isOpen: model.isOpen, + reviews: reviews, ); } diff --git a/lib/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart index a8ca80c6..19939553 100644 --- a/lib/dependency_injection/di_locator.dart +++ b/lib/dependency_injection/di_locator.dart @@ -4,7 +4,7 @@ import 'package:restaurantour/data/network/repositories/yelp_repository.dart'; import 'package:restaurantour/domain/restaurants/use_cases/get_restaurants_use_case.dart'; import 'package:restaurantour/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart'; import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list_view_model.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_view_model.dart'; final locator = GetIt.instance; diff --git a/lib/domain/restaurants/entities/restaurant_entity.dart b/lib/domain/restaurants/entities/restaurant_entity.dart index 784c3769..d6011851 100644 --- a/lib/domain/restaurants/entities/restaurant_entity.dart +++ b/lib/domain/restaurants/entities/restaurant_entity.dart @@ -1,3 +1,5 @@ +import 'package:restaurantour/domain/restaurants/entities/review_entity.dart'; + class RestaurantEntity { final String id; final String name; @@ -5,6 +7,7 @@ class RestaurantEntity { final String price; final double rating; final bool isOpen; + final List reviews; const RestaurantEntity({ required this.id, @@ -13,6 +16,7 @@ class RestaurantEntity { required this.price, required this.rating, required this.isOpen, + required this.reviews, }); @override @@ -25,7 +29,8 @@ class RestaurantEntity { other.heroImage == heroImage && other.price == price && other.rating == rating && - other.isOpen == isOpen; + other.isOpen == isOpen && + other.reviews == reviews; } @override @@ -35,6 +40,7 @@ class RestaurantEntity { heroImage.hashCode ^ price.hashCode ^ rating.hashCode ^ - isOpen.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/main.dart b/lib/main.dart index 07c94448..c5383ec2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; import 'package:restaurantour/dependency_injection/di_locator.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list_page.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_page.dart'; void main() { setupLocator(); diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart new file mode 100644 index 00000000..6d8165ce --- /dev/null +++ b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; + +class RestaurantDetailPage extends StatelessWidget { + const RestaurantDetailPage({ + Key? key, + required this.restaurant, + }) : super(key: key); + final RestaurantEntity restaurant; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Restaurant Detail '), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + // Navigate back to the previous page + Navigator.pop(context); + }, + ), + ), + 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 name + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + restaurant.name, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + ), + // Display the restaurant rating + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + 'Rating: ${restaurant.rating}', + style: const TextStyle( + fontSize: 18, + ), + ), + ), + // Display the restaurant price + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + 'Price: ${restaurant.price}', + style: const TextStyle( + fontSize: 18, + ), + ), + ), + // Display the restaurant open status + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + 'Open: ${restaurant.isOpen ? 'Yes' : 'No'}', + style: const TextStyle( + fontSize: 18, + ), + ), + ), + // Display the restaurant reviews + Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: restaurant.reviews + .map( + (review) => ListTile( + // leading: CircleAvatar( + // backgroundImage: + // NetworkImage(review.author.profileImageUrl), + // ), + title: Text(review.author.name), + subtitle: Text(review.comment), + trailing: Text('${review.rating}'), + ), + ) + .toList(), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/view/restaurants/restaurant_detail_page.dart b/lib/view/restaurants/restaurant_detail_page.dart deleted file mode 100644 index 05cfa501..00000000 --- a/lib/view/restaurants/restaurant_detail_page.dart +++ /dev/null @@ -1,72 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; - -class RestaurantDetailPage extends StatelessWidget { - const RestaurantDetailPage({ - Key? key, - required this.restaurant, - }) : super(key: key); - final RestaurantEntity restaurant; - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: const Text('Restaurant Detail'), - leading: IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () { - // Navigate back to the previous page - Navigator.pop(context); - }, - ), - ), - body: Column( - children: [ - Image.network( - restaurant.heroImage, - fit: BoxFit.cover, - height: 200, - width: double.infinity, - ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - restaurant.name, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - Text( - restaurant.price, - style: const TextStyle( - fontSize: 18, - fontWeight: FontWeight.w500, - ), - ), - Text( - 'Rating: ${restaurant.rating}', - style: const TextStyle( - fontSize: 18, - fontWeight: FontWeight.w500, - ), - ), - Text( - 'Open: ${restaurant.isOpen}', - style: const TextStyle( - fontSize: 18, - fontWeight: FontWeight.w500, - ), - ), - ], - ), - ), - ], - ), - ); - } -} diff --git a/lib/view/restaurants/restaurant_list_page.dart b/lib/view/restaurants/restaurant_list/restaurant_list_page.dart similarity index 97% rename from lib/view/restaurants/restaurant_list_page.dart rename to lib/view/restaurants/restaurant_list/restaurant_list_page.dart index d8ce19ac..5476f306 100644 --- a/lib/view/restaurants/restaurant_list_page.dart +++ b/lib/view/restaurants/restaurant_list/restaurant_list_page.dart @@ -2,9 +2,9 @@ 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/view/restaurants/restaurant_detail_page.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list_view_model.dart'; +import 'package:restaurantour/view/restaurants/restaurant_detail/restaurant_detail_page.dart'; import 'package:restaurantour/design_system/restaurant_list_tile.dart'; +import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_view_model.dart'; class RestaurantListPage extends StatelessWidget { const RestaurantListPage({Key? key}) : super(key: key); diff --git a/lib/view/restaurants/restaurant_list_view_model.dart b/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart similarity index 100% rename from lib/view/restaurants/restaurant_list_view_model.dart rename to lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart From 642a197a0f91a1540e5f071c6bdcf3877cb49e09 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 19:11:35 -0500 Subject: [PATCH 11/16] refactor: adding data source layer --- .../shared_preferences_repository.dart | 6 ++-- .../yelp_source.dart} | 31 ++----------------- lib/dependency_injection/di_locator.dart | 30 +++++++++++++----- .../exceptions/mapper_exception.dart | 0 lib/{data => domain}/restaurant_mapper.dart | 2 +- .../restaurant_repository_impl.dart | 31 +++++++++++++++++++ .../shared_preferences_repository_impl.dart | 22 +++++++++++++ .../restaurant_repository.dart | 0 .../shared_preferences_repository.dart} | 2 +- .../use_cases/get_restaurants_use_case.dart | 2 +- .../save_favorite_restaurant_use_case.dart | 4 +-- .../watch_favorite_restaurants_use_case.dart | 4 +-- 12 files changed, 88 insertions(+), 46 deletions(-) rename lib/data/{network/repositories => sources}/shared_preferences_repository.dart (78%) rename lib/data/{network/repositories/yelp_repository.dart => sources/yelp_source.dart} (74%) rename lib/{data => domain}/exceptions/mapper_exception.dart (100%) rename lib/{data => domain}/restaurant_mapper.dart (95%) create mode 100644 lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart create mode 100644 lib/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart rename lib/domain/restaurants/{ => repositories}/repository_interfaces/restaurant_repository.dart (100%) rename lib/domain/restaurants/{repository_interfaces/preferences_repository.dart => repositories/repository_interfaces/shared_preferences_repository.dart} (78%) diff --git a/lib/data/network/repositories/shared_preferences_repository.dart b/lib/data/sources/shared_preferences_repository.dart similarity index 78% rename from lib/data/network/repositories/shared_preferences_repository.dart rename to lib/data/sources/shared_preferences_repository.dart index d5231ba3..a44ee30b 100644 --- a/lib/data/network/repositories/shared_preferences_repository.dart +++ b/lib/data/sources/shared_preferences_repository.dart @@ -1,14 +1,14 @@ import 'dart:async'; -import 'package:restaurantour/domain/restaurants/repository_interfaces/preferences_repository.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; import 'package:shared_preferences/shared_preferences.dart'; -/// A [PreferencesRepository] implementation that uses [SharedPreferences] as the +/// A [SharedPreferencesRepository] implementation that uses [SharedPreferences] as the /// underlying storage. /// /// Should be replaced with a more robust solution in a production environment. -class SharedPreferencesRepository extends PreferencesRepository { +class SharedPreferencesSource extends SharedPreferencesRepository { static const _key = 'favorite_restaurants'; final StreamController> _controller = diff --git a/lib/data/network/repositories/yelp_repository.dart b/lib/data/sources/yelp_source.dart similarity index 74% rename from lib/data/network/repositories/yelp_repository.dart rename to lib/data/sources/yelp_source.dart index 35a7e503..9843c5ca 100644 --- a/lib/data/network/repositories/yelp_repository.dart +++ b/lib/data/sources/yelp_source.dart @@ -1,19 +1,15 @@ import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; -import 'package:restaurantour/data/exceptions/mapper_exception.dart'; import 'package:restaurantour/data/exceptions/network_exception.dart'; import 'package:restaurantour/data/models/restaurant.dart'; -import 'package:restaurantour/data/restaurant_mapper.dart'; -import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; -import 'package:restaurantour/domain/restaurants/repository_interfaces/restaurant_repository.dart'; const _apiKey = 'wfYIpeyetAPJbQYg5ITUE4wxzqCvoEQM5FQyW9Xq4SGJG52vkefWY_Irq9yg_TKpXRYJUgTO48W_fVXReEABY919sT74bHoCAyNH4b0kTe94rmEWFWNo1GjFxUXjZXYx'; -class YelpRepository extends RestaurantsRepository { +class YelpSource { late Dio dio; - YelpRepository({ + YelpSource({ @visibleForTesting Dio? dio, }) : dio = dio ?? Dio( @@ -65,7 +61,7 @@ class YelpRepository extends RestaurantsRepository { /// } /// - Future?> getRestaurantsFromApi({int offset = 0}) async { + Future?> getRestaurants({int offset = 0}) async { try { final response = await dio.post>( '/v3/graphql', @@ -123,25 +119,4 @@ query getRestaurants { } '''; } - - @override - Future> getRestaurants(int offset) async { - if (offset != 0) { - //wont call api to prevent exceeding limit - print('calling api with offset: $offset'); - return Future.value([]); - } - final result = await getRestaurantsFromApi(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/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart index 19939553..48b2c91e 100644 --- a/lib/dependency_injection/di_locator.dart +++ b/lib/dependency_injection/di_locator.dart @@ -1,6 +1,8 @@ import 'package:get_it/get_it.dart'; -import 'package:restaurantour/data/network/repositories/shared_preferences_repository.dart'; -import 'package:restaurantour/data/network/repositories/yelp_repository.dart'; +import 'package:restaurantour/data/sources/shared_preferences_repository.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_restaurants_use_case.dart'; import 'package:restaurantour/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart'; import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; @@ -12,24 +14,36 @@ void setupLocator() { // UseCases locator.registerFactory( () => GetRestaurantsUseCase( - locator(), + locator(), ), ); locator.registerFactory( () => SaveFavoriteRestaurantUseCase( - locator(), + locator(), ), ); locator.registerFactory( () => WatchFavoriteRestaurantsUseCase( - locator(), + locator(), ), ); + // Sources + locator.registerLazySingleton(() => YelpSource()); + locator.registerLazySingleton( + () => SharedPreferencesSource(), + ); + // Repositories - locator.registerLazySingleton(() => YelpRepository()); - locator.registerLazySingleton( - () => SharedPreferencesRepository(), + locator.registerLazySingleton( + () => RestaurantRepositoryImpl( + locator(), + ), + ); + locator.registerLazySingleton( + () => SharedPreferencesRepositoryImpl( + locator(), + ), ); // ViewModels diff --git a/lib/data/exceptions/mapper_exception.dart b/lib/domain/exceptions/mapper_exception.dart similarity index 100% rename from lib/data/exceptions/mapper_exception.dart rename to lib/domain/exceptions/mapper_exception.dart diff --git a/lib/data/restaurant_mapper.dart b/lib/domain/restaurant_mapper.dart similarity index 95% rename from lib/data/restaurant_mapper.dart rename to lib/domain/restaurant_mapper.dart index 20ae0b4d..d3bee306 100644 --- a/lib/data/restaurant_mapper.dart +++ b/lib/domain/restaurant_mapper.dart @@ -1,4 +1,4 @@ -import 'package:restaurantour/data/exceptions/mapper_exception.dart'; +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'; 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..f57c4f2e --- /dev/null +++ b/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart @@ -0,0 +1,31 @@ +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 { + if (offset != 0) { + //wont call api to prevent exceeding limit + print('calling api with offset: $offset'); + 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..1d618022 --- /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_repository.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 addFavoriteRestaurant(String restaurantId) { + return _sharedPreferencesRepository.addFavoriteRestaurant(restaurantId); + } + + @override + Future> getFavoriteRestaurants() { + return _sharedPreferencesRepository.getFavoriteRestaurants(); + } + + @override + Stream> watchFavoriteRestaurants() { + return _sharedPreferencesRepository.watchFavoriteRestaurants(); + } +} diff --git a/lib/domain/restaurants/repository_interfaces/restaurant_repository.dart b/lib/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart similarity index 100% rename from lib/domain/restaurants/repository_interfaces/restaurant_repository.dart rename to lib/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart diff --git a/lib/domain/restaurants/repository_interfaces/preferences_repository.dart b/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart similarity index 78% rename from lib/domain/restaurants/repository_interfaces/preferences_repository.dart rename to lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart index 860303b0..80a4152e 100644 --- a/lib/domain/restaurants/repository_interfaces/preferences_repository.dart +++ b/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart @@ -1,4 +1,4 @@ -abstract class PreferencesRepository { +abstract class SharedPreferencesRepository { Future addFavoriteRestaurant(String restaurantId); Future> getFavoriteRestaurants(); Stream> watchFavoriteRestaurants(); diff --git a/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart index e2526332..8c82e27a 100644 --- a/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart +++ b/lib/domain/restaurants/use_cases/get_restaurants_use_case.dart @@ -1,5 +1,5 @@ import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; -import 'package:restaurantour/domain/restaurants/repository_interfaces/restaurant_repository.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/restaurant_repository.dart'; class GetRestaurantsUseCase { final RestaurantsRepository _restaurantsRepository; diff --git a/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart b/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart index 45830e51..69016422 100644 --- a/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart +++ b/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart @@ -1,7 +1,7 @@ -import 'package:restaurantour/domain/restaurants/repository_interfaces/preferences_repository.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; class SaveFavoriteRestaurantUseCase { - final PreferencesRepository _preferencesRepository; + final SharedPreferencesRepository _preferencesRepository; SaveFavoriteRestaurantUseCase(this._preferencesRepository); 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 index b1380e9b..0af5ee88 100644 --- a/lib/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart +++ b/lib/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart @@ -1,9 +1,9 @@ import 'dart:async'; -import 'package:restaurantour/domain/restaurants/repository_interfaces/preferences_repository.dart'; +import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; class WatchFavoriteRestaurantsUseCase { - final PreferencesRepository _preferencesRepository; + final SharedPreferencesRepository _preferencesRepository; WatchFavoriteRestaurantsUseCase(this._preferencesRepository); From 1d69c0aab2a7ef6748d6454bdc18dedf0528ca05 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 20:25:41 -0500 Subject: [PATCH 12/16] chore(restaurant-detail): add price range and cateogry --- lib/design_system/restaurant_details.dart | 22 ++++++++++++++++ lib/design_system/restaurant_list_tile.dart | 8 +++++- lib/domain/restaurant_mapper.dart | 1 + .../entities/restaurant_entity.dart | 4 +++ .../restaurant_detail_page.dart | 25 +++++++++++++------ .../restaurant_detail_view_model.dart | 19 ++++++++++++++ .../restaurant_list/restaurant_list_page.dart | 2 ++ 7 files changed, 72 insertions(+), 9 deletions(-) create mode 100644 lib/design_system/restaurant_details.dart create mode 100644 lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart diff --git a/lib/design_system/restaurant_details.dart b/lib/design_system/restaurant_details.dart new file mode 100644 index 00000000..2a7f5e49 --- /dev/null +++ b/lib/design_system/restaurant_details.dart @@ -0,0 +1,22 @@ +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), + Text(category), + ], + ); + } +} diff --git a/lib/design_system/restaurant_list_tile.dart b/lib/design_system/restaurant_list_tile.dart index 70c87956..50f757e7 100644 --- a/lib/design_system/restaurant_list_tile.dart +++ b/lib/design_system/restaurant_list_tile.dart @@ -1,9 +1,11 @@ import 'package:flutter/material.dart'; +import 'package:restaurantour/design_system/restaurant_details.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; @@ -13,6 +15,7 @@ class RestaurantListTile extends StatelessWidget { required this.imageUrl, required this.name, required this.priceRange, + required this.category, required this.rating, required this.isOpen, this.onTap, @@ -33,7 +36,10 @@ class RestaurantListTile extends StatelessWidget { subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(priceRange), + RestaurantDetails( + price: priceRange, + category: category, + ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ diff --git a/lib/domain/restaurant_mapper.dart b/lib/domain/restaurant_mapper.dart index d3bee306..72966674 100644 --- a/lib/domain/restaurant_mapper.dart +++ b/lib/domain/restaurant_mapper.dart @@ -37,6 +37,7 @@ class RestaurantMapper { heroImage: model.photos?.first ?? '', isOpen: model.isOpen, reviews: reviews, + category: model.categories?.first.title ?? '', ); } diff --git a/lib/domain/restaurants/entities/restaurant_entity.dart b/lib/domain/restaurants/entities/restaurant_entity.dart index d6011851..6d132fb6 100644 --- a/lib/domain/restaurants/entities/restaurant_entity.dart +++ b/lib/domain/restaurants/entities/restaurant_entity.dart @@ -6,6 +6,7 @@ class RestaurantEntity { final String heroImage; final String price; final double rating; + final String category; final bool isOpen; final List reviews; @@ -15,6 +16,7 @@ class RestaurantEntity { required this.heroImage, required this.price, required this.rating, + required this.category, required this.isOpen, required this.reviews, }); @@ -29,6 +31,7 @@ class RestaurantEntity { other.heroImage == heroImage && other.price == price && other.rating == rating && + other.category == category && other.isOpen == isOpen && other.reviews == reviews; } @@ -40,6 +43,7 @@ class RestaurantEntity { heroImage.hashCode ^ price.hashCode ^ rating.hashCode ^ + category.hashCode ^ isOpen.hashCode ^ reviews.hashCode; } diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart index 6d8165ce..d33b6cb7 100644 --- a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart +++ b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:restaurantour/design_system/restaurant_details.dart'; import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; class RestaurantDetailPage extends StatelessWidget { @@ -12,7 +13,9 @@ class RestaurantDetailPage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: const Text('Restaurant Detail '), + title: Text( + restaurant.name, + ), leading: IconButton( icon: const Icon(Icons.arrow_back), onPressed: () { @@ -20,6 +23,14 @@ class RestaurantDetailPage extends StatelessWidget { Navigator.pop(context); }, ), + actions: [ + IconButton( + icon: const Icon(Icons.favorite_border), + onPressed: () { + // Add the restaurant to the user's favorites + }, + ), + ], ), body: SingleChildScrollView( child: Column( @@ -34,17 +45,15 @@ class RestaurantDetailPage extends StatelessWidget { width: double.infinity, ), ), - // Display the restaurant name + // Display the restaurant details Padding( padding: const EdgeInsets.all(8.0), - child: Text( - restaurant.name, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), + child: RestaurantDetails( + price: restaurant.price, + category: restaurant.category, ), ), + // Display the restaurant rating Padding( padding: const EdgeInsets.all(8.0), diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart b/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart new file mode 100644 index 00000000..6af7bffa --- /dev/null +++ b/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart @@ -0,0 +1,19 @@ +import 'package:flutter/foundation.dart'; +import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart'; + +class RestaurantDetailViewModel extends ChangeNotifier { + RestaurantDetailViewModel({ + required RestaurantEntity restaurant, + required SaveFavoriteRestaurantUseCase saveFavoriteRestaurantUseCase, + }) : _restaurant = restaurant, + _saveFavoriteRestaurantUseCase = saveFavoriteRestaurantUseCase; + + final RestaurantEntity _restaurant; + final SaveFavoriteRestaurantUseCase _saveFavoriteRestaurantUseCase; + + void addToFavorites() { + _saveFavoriteRestaurantUseCase(_restaurant.id); + notifyListeners(); + } +} diff --git a/lib/view/restaurants/restaurant_list/restaurant_list_page.dart b/lib/view/restaurants/restaurant_list/restaurant_list_page.dart index 5476f306..071b77dc 100644 --- a/lib/view/restaurants/restaurant_list/restaurant_list_page.dart +++ b/lib/view/restaurants/restaurant_list/restaurant_list_page.dart @@ -103,6 +103,7 @@ class _AllRestaurantsTab extends StatelessWidget { priceRange: restaurant.price, rating: restaurant.rating, isOpen: restaurant.isOpen, + category: restaurant.category, ); }, ), @@ -154,6 +155,7 @@ class _MyFavoritesTab extends StatelessWidget { priceRange: restaurant.price, rating: restaurant.rating, isOpen: restaurant.isOpen, + category: restaurant.category, ); }, ); From 627d18e9965141d3b39d6cd9a679a1d11992b804 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sat, 2 Mar 2024 22:27:05 -0500 Subject: [PATCH 13/16] feat(toggle-favorite): allow favorite toggling --- ...ry.dart => shared_preferences_source.dart} | 20 +- lib/data/sources/yelp_source.dart | 2 +- lib/dependency_injection/di_locator.dart | 52 +++-- lib/design_system/open_status_indicator.dart | 27 +++ lib/design_system/restaurant_details.dart | 1 + lib/design_system/restaurant_list_tile.dart | 57 +++-- .../restaurant_repository_impl.dart | 3 +- .../shared_preferences_repository_impl.dart | 6 +- .../shared_preferences_repository.dart | 2 +- ...t_restaurant_favorite_status_use_case.dart | 13 ++ .../save_favorite_restaurant_use_case.dart | 14 -- .../toggle_favorite_restaurant_use_case.dart | 15 ++ .../restaurant_detail_page.dart | 209 ++++++++++-------- .../restaurant_detail_view_model.dart | 40 +++- .../restaurant_list/restaurant_list_page.dart | 22 +- .../restaurant_list_view_model.dart | 11 +- 16 files changed, 299 insertions(+), 195 deletions(-) rename lib/data/sources/{shared_preferences_repository.dart => shared_preferences_source.dart} (56%) create mode 100644 lib/design_system/open_status_indicator.dart create mode 100644 lib/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart delete mode 100644 lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart create mode 100644 lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart diff --git a/lib/data/sources/shared_preferences_repository.dart b/lib/data/sources/shared_preferences_source.dart similarity index 56% rename from lib/data/sources/shared_preferences_repository.dart rename to lib/data/sources/shared_preferences_source.dart index a44ee30b..fedf11c8 100644 --- a/lib/data/sources/shared_preferences_repository.dart +++ b/lib/data/sources/shared_preferences_source.dart @@ -3,10 +3,8 @@ import 'dart:async'; import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; import 'package:shared_preferences/shared_preferences.dart'; -/// A [SharedPreferencesRepository] implementation that uses [SharedPreferences] as the -/// underlying storage. -/// -/// Should be replaced with a more robust solution in a production environment. +/// 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'; @@ -21,17 +19,21 @@ class SharedPreferencesSource extends SharedPreferencesRepository { } @override - Future addFavoriteRestaurant(String restaurantId) async { + Future toggleFavoriteRestaurant(String restaurantId) async { final prefs = await SharedPreferences.getInstance(); - final favorites = prefs.getStringList(_key) ?? []; - if (!favorites.contains(restaurantId)) { - favorites.add(restaurantId); - await prefs.setStringList(_key, favorites); + 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; } diff --git a/lib/data/sources/yelp_source.dart b/lib/data/sources/yelp_source.dart index 9843c5ca..df0e6171 100644 --- a/lib/data/sources/yelp_source.dart +++ b/lib/data/sources/yelp_source.dart @@ -86,7 +86,7 @@ class YelpSource { String _getQuery(int offset) { return ''' query getRestaurants { - search(location: "Las Vegas", limit: 1, offset: $offset) { + search(location: "Las Vegas", limit: 3, offset: $offset) { total business { id diff --git a/lib/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart index 48b2c91e..52513f9f 100644 --- a/lib/dependency_injection/di_locator.dart +++ b/lib/dependency_injection/di_locator.dart @@ -1,33 +1,18 @@ import 'package:get_it/get_it.dart'; -import 'package:restaurantour/data/sources/shared_preferences_repository.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/save_favorite_restaurant_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/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart'; import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_view_model.dart'; final locator = GetIt.instance; void setupLocator() { - // UseCases - locator.registerFactory( - () => GetRestaurantsUseCase( - locator(), - ), - ); - locator.registerFactory( - () => SaveFavoriteRestaurantUseCase( - locator(), - ), - ); - locator.registerFactory( - () => WatchFavoriteRestaurantsUseCase( - locator(), - ), - ); - // Sources locator.registerLazySingleton(() => YelpSource()); locator.registerLazySingleton( @@ -46,12 +31,39 @@ void setupLocator() { ), ); + // UseCases + locator.registerFactory( + () => GetRestaurantsUseCase( + locator(), + ), + ); + locator.registerFactory( + () => ToggleFavoriteRestaurantUseCase( + locator(), + ), + ); + locator.registerFactory( + () => WatchFavoriteRestaurantsUseCase( + locator(), + ), + ); + locator.registerFactory( + () => GetRestaurantFavoriteStatusUseCase( + locator(), + ), + ); + // ViewModels locator.registerLazySingleton( () => RestaurantListViewModel( locator(), - locator(), locator(), ), ); + locator.registerFactory( + () => RestaurantDetailViewModel( + locator(), + locator(), + ), + ); } 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_details.dart b/lib/design_system/restaurant_details.dart index 2a7f5e49..b59acf67 100644 --- a/lib/design_system/restaurant_details.dart +++ b/lib/design_system/restaurant_details.dart @@ -15,6 +15,7 @@ class RestaurantDetails extends StatelessWidget { 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 index 50f757e7..07fdd114 100644 --- a/lib/design_system/restaurant_list_tile.dart +++ b/lib/design_system/restaurant_list_tile.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:restaurantour/design_system/open_status_indicator.dart'; import 'package:restaurantour/design_system/restaurant_details.dart'; class RestaurantListTile extends StatelessWidget { @@ -25,36 +26,32 @@ class RestaurantListTile extends StatelessWidget { Widget build(BuildContext context) { return GestureDetector( onTap: onTap, - child: ListTile( - leading: Image.network( - imageUrl, - width: 70, - height: 70, - fit: BoxFit.cover, - ), - title: Text(name), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - RestaurantDetails( - price: priceRange, - category: category, - ), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - _StarRating(rating: rating), - Container( - width: 10, - height: 10, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: isOpen ? Colors.green : Colors.red, - ), - ), - ], - ), - ], + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: ListTile( + leading: 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: [ + _StarRating(rating: rating), + OpenStatusIndicator(isOpen: isOpen), + ], + ), + ], + ), ), ), ); diff --git a/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart b/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart index f57c4f2e..61b7258b 100644 --- a/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart +++ b/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart @@ -10,11 +10,12 @@ class RestaurantRepositoryImpl implements RestaurantsRepository { @override Future> getRestaurants(int offset) async { + // Remove this if clause to enable pagination if (offset != 0) { //wont call api to prevent exceeding limit - print('calling api with offset: $offset'); return Future.value([]); } + final result = await _yelpSource.getRestaurants(offset: offset); if (result == null) { throw Exception('Failed to fetch restaurants'); 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 index 1d618022..0f65ab86 100644 --- a/lib/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart +++ b/lib/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart @@ -1,4 +1,4 @@ -import 'package:restaurantour/data/sources/shared_preferences_repository.dart'; +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 { @@ -6,8 +6,8 @@ class SharedPreferencesRepositoryImpl implements SharedPreferencesRepository { SharedPreferencesRepositoryImpl(this._sharedPreferencesRepository); @override - Future addFavoriteRestaurant(String restaurantId) { - return _sharedPreferencesRepository.addFavoriteRestaurant(restaurantId); + Future toggleFavoriteRestaurant(String restaurantId) { + return _sharedPreferencesRepository.toggleFavoriteRestaurant(restaurantId); } @override diff --git a/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart b/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart index 80a4152e..68dea69a 100644 --- a/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart +++ b/lib/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart @@ -1,5 +1,5 @@ abstract class SharedPreferencesRepository { - Future addFavoriteRestaurant(String restaurantId); + 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..31101d10 --- /dev/null +++ b/lib/domain/restaurants/use_cases/get_restaurant_favorite_status_use_case.dart @@ -0,0 +1,13 @@ +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/save_favorite_restaurant_use_case.dart b/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart deleted file mode 100644 index 69016422..00000000 --- a/lib/domain/restaurants/use_cases/save_favorite_restaurant_use_case.dart +++ /dev/null @@ -1,14 +0,0 @@ -import 'package:restaurantour/domain/restaurants/repositories/repository_interfaces/shared_preferences_repository.dart'; - -class SaveFavoriteRestaurantUseCase { - final SharedPreferencesRepository _preferencesRepository; - - SaveFavoriteRestaurantUseCase(this._preferencesRepository); - - Future call(String restaurantId) async { - await _preferencesRepository.addFavoriteRestaurant(restaurantId); - final currentFavorites = - await _preferencesRepository.getFavoriteRestaurants(); - print('Current favorites: $currentFavorites'); - } -} 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..fa87a637 --- /dev/null +++ b/lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart @@ -0,0 +1,15 @@ +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); + + // print favorites + final favorites = await _preferencesRepository.getFavoriteRestaurants(); + print('Favorites: $favorites'); + } +} diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart index d33b6cb7..6799f8b9 100644 --- a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart +++ b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart @@ -1,6 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:restaurantour/dependency_injection/di_locator.dart'; import 'package:restaurantour/design_system/restaurant_details.dart'; import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; +import 'package:restaurantour/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart'; +import 'package:provider/provider.dart'; class RestaurantDetailPage extends StatelessWidget { const RestaurantDetailPage({ @@ -11,101 +14,127 @@ class RestaurantDetailPage extends StatelessWidget { @override Widget build(BuildContext context) { - 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: const Icon(Icons.favorite_border), - onPressed: () { - // Add the restaurant to the user's 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(8.0), - child: RestaurantDetails( - price: restaurant.price, - category: restaurant.category, - ), - ), - - // Display the restaurant rating - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - 'Rating: ${restaurant.rating}', - style: const TextStyle( - fontSize: 18, + return ChangeNotifierProvider( + create: (context) => + locator()..init(restaurant), + builder: (context, child) { + return Consumer( + builder: (context, viewModel, child) { + return Scaffold( + appBar: AppBar( + title: Text( + restaurant.name, ), - ), - ), - // Display the restaurant price - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - 'Price: ${restaurant.price}', - style: const TextStyle( - fontSize: 18, - ), - ), - ), - // Display the restaurant open status - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - 'Open: ${restaurant.isOpen ? 'Yes' : 'No'}', - style: const TextStyle( - fontSize: 18, + 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', + ), + ), + ); + }, + ), + ], ), - ), - // Display the restaurant reviews - Padding( - padding: const EdgeInsets.all(8.0), - child: Column( - children: restaurant.reviews - .map( - (review) => ListTile( - // leading: CircleAvatar( - // backgroundImage: - // NetworkImage(review.author.profileImageUrl), - // ), - title: Text(review.author.name), - subtitle: Text(review.comment), - trailing: Text('${review.rating}'), + 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, ), - ) - .toList(), + ), + // Display the restaurant details + Padding( + padding: const EdgeInsets.all(8.0), + child: RestaurantDetails( + price: restaurant.price, + category: restaurant.category, + ), + ), + // Display the restaurant rating + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + 'Rating: ${restaurant.rating}', + style: const TextStyle( + fontSize: 18, + ), + ), + ), + // Display the restaurant price + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + 'Price: ${restaurant.price}', + style: const TextStyle( + fontSize: 18, + ), + ), + ), + // Display the restaurant open status + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + 'Open: ${restaurant.isOpen ? 'Yes' : 'No'}', + style: const TextStyle( + fontSize: 18, + ), + ), + ), + // Display the restaurant reviews + Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: restaurant.reviews + .map( + (review) => ListTile( + // leading: CircleAvatar( + // backgroundImage: + // NetworkImage(review.author.profileImageUrl), + // ), + title: Text(review.author.name), + subtitle: Text(review.comment), + trailing: Text('${review.rating}'), + ), + ) + .toList(), + ), + ), + ], + ), ), - ), - ], - ), - ), + ); + }, + ); + }, ); } } diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart b/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart index 6af7bffa..361203db 100644 --- a/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart +++ b/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart @@ -1,19 +1,39 @@ import 'package:flutter/foundation.dart'; import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; -import 'package:restaurantour/domain/restaurants/use_cases/save_favorite_restaurant_use_case.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({ - required RestaurantEntity restaurant, - required SaveFavoriteRestaurantUseCase saveFavoriteRestaurantUseCase, - }) : _restaurant = restaurant, - _saveFavoriteRestaurantUseCase = saveFavoriteRestaurantUseCase; + RestaurantDetailViewModel( + this._toggleFavoriteRestaurantUseCase, + this._getRestaurantFavoriteStatusUseCase, + ); - final RestaurantEntity _restaurant; - final SaveFavoriteRestaurantUseCase _saveFavoriteRestaurantUseCase; + final ToggleFavoriteRestaurantUseCase _toggleFavoriteRestaurantUseCase; + final GetRestaurantFavoriteStatusUseCase _getRestaurantFavoriteStatusUseCase; - void addToFavorites() { - _saveFavoriteRestaurantUseCase(_restaurant.id); + 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); + print('isFavorite: $_isFavorite'); + notifyListeners(); + } + + void toggleFavorite() async { + if (_restaurant == null) return; + await _toggleFavoriteRestaurantUseCase(_restaurant!.id); + _isFavorite = !_isFavorite; notifyListeners(); } } diff --git a/lib/view/restaurants/restaurant_list/restaurant_list_page.dart b/lib/view/restaurants/restaurant_list/restaurant_list_page.dart index 071b77dc..d78c0c69 100644 --- a/lib/view/restaurants/restaurant_list/restaurant_list_page.dart +++ b/lib/view/restaurants/restaurant_list/restaurant_list_page.dart @@ -132,8 +132,10 @@ class _MyFavoritesTab extends StatelessWidget { ); } - // display favorite restaurants - final favoriteRestaurants = viewModel.favoriteRestaurants; + final favoriteRestaurants = viewModel.restaurants + .where((restaurant) => + viewModel.favoriteRestaurants.contains(restaurant.id)) + .toList(); if (favoriteRestaurants.isEmpty) { return const Center( @@ -145,11 +147,19 @@ class _MyFavoritesTab extends StatelessWidget { return ListView.builder( itemCount: favoriteRestaurants.length, itemBuilder: (context, index) { - final restaurantId = favoriteRestaurants[index]; - final restaurant = viewModel.restaurants.firstWhere( - (element) => element.id == restaurantId, - ); + 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, diff --git a/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart b/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart index 6ef66119..f8745219 100644 --- a/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart +++ b/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart @@ -3,7 +3,6 @@ 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/save_favorite_restaurant_use_case.dart'; import 'package:restaurantour/domain/restaurants/use_cases/watch_favorite_restaurants_use_case.dart'; enum RestaurantListState { @@ -15,12 +14,10 @@ enum RestaurantListState { class RestaurantListViewModel extends ChangeNotifier { final GetRestaurantsUseCase _getRestaurantsUseCase; - final SaveFavoriteRestaurantUseCase _saveFavoriteRestaurantUseCase; final WatchFavoriteRestaurantsUseCase _watchFavoriteRestaurantsUseCase; RestaurantListViewModel( this._getRestaurantsUseCase, - this._saveFavoriteRestaurantUseCase, this._watchFavoriteRestaurantsUseCase, ); @@ -43,8 +40,7 @@ class RestaurantListViewModel extends ChangeNotifier { getRestaurants(); _favoritesSubscription?.cancel(); _favoritesSubscription = _watchFavoriteRestaurantsUseCase().listen((event) { - _favoriteRestaurants?.add(event as String); - print('favorites: $_favoriteRestaurants'); + _favoriteRestaurants = event; notifyListeners(); }); } @@ -58,7 +54,6 @@ class RestaurantListViewModel extends ChangeNotifier { Future?> getRestaurants() async { try { if (_state == RestaurantListState.loadingMore) return _restaurants; - print('fetching restaurants'); final result = await _getRestaurantsUseCase(_offset); _restaurants.addAll(result); @@ -72,8 +67,4 @@ class RestaurantListViewModel extends ChangeNotifier { return null; } } - - Future saveFavorite(String restaurantId) async { - await _saveFavoriteRestaurantUseCase(restaurantId); - } } From 80241a3a7873efea8970a3aa7b6835a40f62c690 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sun, 3 Mar 2024 07:03:33 -0500 Subject: [PATCH 14/16] chore(restaurant-detail): reviews, address --- lib/dependency_injection/di_locator.dart | 4 +- lib/design_system/restaurant_address.dart | 37 ++++ lib/design_system/restaurant_list_tile.dart | 31 +-- lib/design_system/restaurant_rating.dart | 46 +++++ lib/design_system/restaurant_stars.dart | 29 +++ lib/domain/restaurant_mapper.dart | 4 +- .../entities/restaurant_entity.dart | 4 + .../restaurant_repository_impl.dart | 4 +- ...t_restaurant_favorite_status_use_case.dart | 1 + .../toggle_favorite_restaurant_use_case.dart | 4 - lib/main.dart | 2 +- .../restaurant_detail_page.dart | 189 ++++++++++++++++++ .../restaurant_detail_view_model.dart | 1 - .../restaurant_list/restaurant_list_page.dart | 4 +- .../restaurant_list_view_model.dart | 13 +- .../restaurant_detail_page.dart | 140 ------------- pubspec.lock | 14 +- pubspec.yaml | 7 +- .../restaurant_repository_impl.dart | 1 + .../shared_preferences_repository_impl.dart | 0 .../restaurant_list_view_model_test.dart | 36 ++++ test/test_utils/mocks.dart | 15 ++ test/test_utils/mocks.mocks.dart | 168 ++++++++++++++++ 23 files changed, 560 insertions(+), 194 deletions(-) create mode 100644 lib/design_system/restaurant_address.dart create mode 100644 lib/design_system/restaurant_rating.dart create mode 100644 lib/design_system/restaurant_stars.dart create mode 100644 lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart rename lib/{view => presentation}/restaurants/restaurant_detail/restaurant_detail_view_model.dart (97%) rename lib/{view => presentation}/restaurants/restaurant_list/restaurant_list_page.dart (95%) rename lib/{view => presentation}/restaurants/restaurant_list/restaurant_list_view_model.dart (88%) delete mode 100644 lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart create mode 100644 test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart create mode 100644 test/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart create mode 100644 test/presentation/restaurant_list_view_model_test.dart create mode 100644 test/test_utils/mocks.dart create mode 100644 test/test_utils/mocks.mocks.dart diff --git a/lib/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart index 52513f9f..358dc409 100644 --- a/lib/dependency_injection/di_locator.dart +++ b/lib/dependency_injection/di_locator.dart @@ -7,8 +7,8 @@ import 'package:restaurantour/domain/restaurants/use_cases/get_restaurant_favori 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/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_view_model.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; 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_list_tile.dart b/lib/design_system/restaurant_list_tile.dart index 07fdd114..26800823 100644 --- a/lib/design_system/restaurant_list_tile.dart +++ b/lib/design_system/restaurant_list_tile.dart @@ -1,6 +1,7 @@ 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; @@ -46,7 +47,7 @@ class RestaurantListTile extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - _StarRating(rating: rating), + RestaurantStars(rating: rating), OpenStatusIndicator(isOpen: isOpen), ], ), @@ -57,31 +58,3 @@ class RestaurantListTile extends StatelessWidget { ); } } - -class _StarRating extends StatelessWidget { - final double rating; - - const _StarRating({ - Key? key, - required this.rating, - }) : super(key: key); - - @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/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/restaurant_mapper.dart b/lib/domain/restaurant_mapper.dart index 72966674..a6e87e7d 100644 --- a/lib/domain/restaurant_mapper.dart +++ b/lib/domain/restaurant_mapper.dart @@ -22,7 +22,8 @@ class RestaurantMapper { author: UserEntity( id: review.user?.id ?? '', name: review.user?.name ?? '', - profileImageUrl: review.user?.imageUrl ?? '', + profileImageUrl: review.user?.imageUrl ?? + 'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/batman_hero_avatar_comics-512.png', ), ), ) @@ -37,6 +38,7 @@ class RestaurantMapper { heroImage: model.photos?.first ?? '', isOpen: model.isOpen, reviews: reviews, + address: model.location?.formattedAddress ?? '', category: model.categories?.first.title ?? '', ); } diff --git a/lib/domain/restaurants/entities/restaurant_entity.dart b/lib/domain/restaurants/entities/restaurant_entity.dart index 6d132fb6..1d760dbe 100644 --- a/lib/domain/restaurants/entities/restaurant_entity.dart +++ b/lib/domain/restaurants/entities/restaurant_entity.dart @@ -7,6 +7,7 @@ class RestaurantEntity { final String price; final double rating; final String category; + final String address; final bool isOpen; final List reviews; @@ -17,6 +18,7 @@ class RestaurantEntity { required this.price, required this.rating, required this.category, + required this.address, required this.isOpen, required this.reviews, }); @@ -32,6 +34,7 @@ class RestaurantEntity { other.price == price && other.rating == rating && other.category == category && + other.address == address && other.isOpen == isOpen && other.reviews == reviews; } @@ -44,6 +47,7 @@ class RestaurantEntity { price.hashCode ^ rating.hashCode ^ category.hashCode ^ + address.hashCode ^ isOpen.hashCode ^ reviews.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 index 61b7258b..d6d13754 100644 --- a/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart +++ b/lib/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart @@ -10,8 +10,8 @@ class RestaurantRepositoryImpl implements RestaurantsRepository { @override Future> getRestaurants(int offset) async { - // Remove this if clause to enable pagination - if (offset != 0) { + // TODO(jvelezos): Remove this if clause to enable pagination + if (offset > 45) { //wont call api to prevent exceeding limit return Future.value([]); } 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 index 31101d10..b4c4a7b1 100644 --- 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 @@ -8,6 +8,7 @@ class GetRestaurantFavoriteStatusUseCase { Future call(String restaurantId) async { final List favoriteRestaurants = await _sharedPreferencesRepository.getFavoriteRestaurants(); + return favoriteRestaurants.contains(restaurantId); } } 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 index fa87a637..b98cec50 100644 --- a/lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart +++ b/lib/domain/restaurants/use_cases/toggle_favorite_restaurant_use_case.dart @@ -7,9 +7,5 @@ class ToggleFavoriteRestaurantUseCase { Future call(String restaurantId) async { await _preferencesRepository.toggleFavoriteRestaurant(restaurantId); - - // print favorites - final favorites = await _preferencesRepository.getFavoriteRestaurants(); - print('Favorites: $favorites'); } } diff --git a/lib/main.dart b/lib/main.dart index c5383ec2..f8364ca0 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; import 'package:restaurantour/dependency_injection/di_locator.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_page.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_page.dart'; void main() { setupLocator(); 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..c35363f6 --- /dev/null +++ b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart @@ -0,0 +1,189 @@ +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'; + +const detailSpacing = 24.0; +const detailVerticalSpacing = 12.0; + +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(detailSpacing), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + RestaurantDetails( + price: restaurant.price, + category: restaurant.category, + ), + OpenStatusIndicator(isOpen: restaurant.isOpen), + ], + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: detailSpacing), + child: Divider( + color: Colors.grey, + ), + ), + // Display Address + Padding( + padding: const EdgeInsets.all(detailSpacing), + child: RestaurantAddress( + address: restaurant.address, + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: detailSpacing), + child: Divider( + color: Colors.grey, + ), + ), + + // Display the restaurant rating + Padding( + padding: const EdgeInsets.all(detailSpacing), + child: RestaurantRating( + rating: restaurant.rating, + ), + ), + const Padding( + padding: EdgeInsets.symmetric(horizontal: detailSpacing), + child: Divider( + color: Colors.grey, + ), + ), + Padding( + padding: const EdgeInsets.all(detailSpacing), + child: Align( + alignment: Alignment.topLeft, + child: Text( + '${restaurant.reviews.length} Reviews', + ), + ), + ), + + // Display the restaurant reviews + Padding( + padding: + const EdgeInsets.symmetric(horizontal: detailSpacing) + .copyWith(bottom: detailSpacing), + child: Column( + children: restaurant.reviews + .map( + (review) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + RestaurantStars(rating: restaurant.rating), + const SizedBox(height: detailVerticalSpacing), + Text( + review.comment, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: detailVerticalSpacing), + Row( + children: [ + CircleAvatar( + backgroundImage: NetworkImage( + review.author.profileImageUrl, + ), + ), + const SizedBox( + width: 4, + ), + Text(review.author.name), + ], + ), + const SizedBox(height: detailVerticalSpacing), + const Divider( + color: Colors.grey, + ), + ], + ), + ) + .toList(), + ), + ), + ], + ), + ), + ); + }, + ); + }, + ); + } +} diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart similarity index 97% rename from lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart rename to lib/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart index 361203db..eacae577 100644 --- a/lib/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart +++ b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_view_model.dart @@ -26,7 +26,6 @@ class RestaurantDetailViewModel extends ChangeNotifier { void getFavoriteStatus() async { if (_restaurant == null) return; _isFavorite = await _getRestaurantFavoriteStatusUseCase(_restaurant!.id); - print('isFavorite: $_isFavorite'); notifyListeners(); } diff --git a/lib/view/restaurants/restaurant_list/restaurant_list_page.dart b/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart similarity index 95% rename from lib/view/restaurants/restaurant_list/restaurant_list_page.dart rename to lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart index d78c0c69..5f178f54 100644 --- a/lib/view/restaurants/restaurant_list/restaurant_list_page.dart +++ b/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart @@ -2,9 +2,9 @@ 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/view/restaurants/restaurant_detail/restaurant_detail_page.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart'; import 'package:restaurantour/design_system/restaurant_list_tile.dart'; -import 'package:restaurantour/view/restaurants/restaurant_list/restaurant_list_view_model.dart'; +import 'package:restaurantour/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart'; class RestaurantListPage extends StatelessWidget { const RestaurantListPage({Key? key}) : super(key: key); diff --git a/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart b/lib/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart similarity index 88% rename from lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart rename to lib/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart index f8745219..7b8e3ef1 100644 --- a/lib/view/restaurants/restaurant_list/restaurant_list_view_model.dart +++ b/lib/presentation/restaurants/restaurant_list/restaurant_list_view_model.dart @@ -51,20 +51,21 @@ class RestaurantListViewModel extends ChangeNotifier { _favoritesSubscription?.cancel(); } - Future?> getRestaurants() async { + Future getRestaurants() async { try { - if (_state == RestaurantListState.loadingMore) return _restaurants; + 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; - notifyListeners(); - return result; } catch (e) { _state = RestaurantListState.error; - notifyListeners(); - return null; } + notifyListeners(); } } diff --git a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart b/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart deleted file mode 100644 index 6799f8b9..00000000 --- a/lib/view/restaurants/restaurant_detail/restaurant_detail_page.dart +++ /dev/null @@ -1,140 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:restaurantour/dependency_injection/di_locator.dart'; -import 'package:restaurantour/design_system/restaurant_details.dart'; -import 'package:restaurantour/domain/restaurants/entities/restaurant_entity.dart'; -import 'package:restaurantour/view/restaurants/restaurant_detail/restaurant_detail_view_model.dart'; -import 'package:provider/provider.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(8.0), - child: RestaurantDetails( - price: restaurant.price, - category: restaurant.category, - ), - ), - // Display the restaurant rating - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - 'Rating: ${restaurant.rating}', - style: const TextStyle( - fontSize: 18, - ), - ), - ), - // Display the restaurant price - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - 'Price: ${restaurant.price}', - style: const TextStyle( - fontSize: 18, - ), - ), - ), - // Display the restaurant open status - Padding( - padding: const EdgeInsets.all(8.0), - child: Text( - 'Open: ${restaurant.isOpen ? 'Yes' : 'No'}', - style: const TextStyle( - fontSize: 18, - ), - ), - ), - // Display the restaurant reviews - Padding( - padding: const EdgeInsets.all(8.0), - child: Column( - children: restaurant.reviews - .map( - (review) => ListTile( - // leading: CircleAvatar( - // backgroundImage: - // NetworkImage(review.author.profileImageUrl), - // ), - title: Text(review.author.name), - subtitle: Text(review.comment), - trailing: Text('${review.rating}'), - ), - ) - .toList(), - ), - ), - ], - ), - ), - ); - }, - ); - }, - ); - } -} diff --git a/pubspec.lock b/pubspec.lock index 17e5d2e8..2a6f7dae 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -257,7 +257,7 @@ packages: source: hosted version: "3.2.0" get_it: - dependency: "direct dev" + dependency: "direct main" description: name: get_it sha256: e6017ce7fdeaf218dc51a100344d8cb70134b80e28b760f8bb23c242437bafd7 @@ -384,6 +384,14 @@ packages: url: "https://pub.dev" source: hosted 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: @@ -473,7 +481,7 @@ packages: source: hosted version: "1.5.1" provider: - dependency: "direct dev" + dependency: "direct main" description: name: provider sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c @@ -497,7 +505,7 @@ packages: source: hosted version: "1.2.3" shared_preferences: - dependency: "direct dev" + dependency: "direct main" description: name: shared_preferences sha256: "81429e4481e1ccfb51ede496e916348668fd0921627779233bd24cc3ff6abd02" diff --git a/pubspec.yaml b/pubspec.yaml index cbe4bf92..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,9 +26,7 @@ dev_dependencies: flutter_lints: ^1.0.2 build_runner: ^2.4.8 json_serializable: ^6.7.1 - get_it: ^7.6.7 - provider: - shared_preferences: + mockito: flutter: uses-material-design: true diff --git a/test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart b/test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart @@ -0,0 +1 @@ + diff --git a/test/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart b/test/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart new file mode 100644 index 00000000..e69de29b diff --git a/test/presentation/restaurant_list_view_model_test.dart b/test/presentation/restaurant_list_view_model_test.dart new file mode 100644 index 00000000..64154a19 --- /dev/null +++ b/test/presentation/restaurant_list_view_model_test.dart @@ -0,0 +1,36 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/mockito.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, + ); + }); + + 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); + }); + + test('get restaurants should get more restaurants', () async { + await viewModel.getRestaurants(); + verify(mockGetRestaurantsUseCase(0)).called(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, + ); +} From 2ce0cdac805243038e01aeabe64c6287015a5919 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sun, 3 Mar 2024 09:02:18 -0500 Subject: [PATCH 15/16] test: restaurant list tests --- lib/dependency_injection/di_locator.dart | 9 ++ lib/design_system/restaurant_list_tile.dart | 14 ++-- .../restaurant_detail_page.dart | 42 ++++++---- .../restaurant_list/restaurant_list_page.dart | 11 +-- lib/presentation/utils/constants.dart | 12 +++ .../restaurant_repository_impl.dart | 1 - .../shared_preferences_repository_impl.dart | 0 .../restaurant_list_page_test.dart | 83 +++++++++++++++++++ .../restaurant_list_view_model_test.dart | 26 ++++-- 9 files changed, 163 insertions(+), 35 deletions(-) create mode 100644 lib/presentation/utils/constants.dart delete mode 100644 test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart delete mode 100644 test/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart create mode 100644 test/presentation/restaurants/restaurant_list/restaurant_list_page_test.dart rename test/presentation/{ => restaurants/restaurant_list}/restaurant_list_view_model_test.dart (59%) diff --git a/lib/dependency_injection/di_locator.dart b/lib/dependency_injection/di_locator.dart index 358dc409..b575c0a8 100644 --- a/lib/dependency_injection/di_locator.dart +++ b/lib/dependency_injection/di_locator.dart @@ -1,3 +1,4 @@ +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'; @@ -67,3 +68,11 @@ void setupLocator() { ), ); } + +/// Regisers an object of type T +/// +/// only available for testing +@visibleForTesting +void testRegister(T object) { + locator.registerSingleton(object); +} diff --git a/lib/design_system/restaurant_list_tile.dart b/lib/design_system/restaurant_list_tile.dart index 26800823..b48658f4 100644 --- a/lib/design_system/restaurant_list_tile.dart +++ b/lib/design_system/restaurant_list_tile.dart @@ -30,12 +30,14 @@ class RestaurantListTile extends StatelessWidget { child: Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: ListTile( - leading: Image.network( - imageUrl, - width: 88, - height: 88, - fit: BoxFit.cover, - ), + leading: imageUrl.isEmpty + ? const SizedBox.shrink() + : Image.network( + imageUrl, + width: 88, + height: 88, + fit: BoxFit.cover, + ), title: Text(name), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart index c35363f6..32f0ac85 100644 --- a/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart +++ b/lib/presentation/restaurants/restaurant_detail/restaurant_detail_page.dart @@ -8,9 +8,7 @@ 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'; - -const detailSpacing = 24.0; -const detailVerticalSpacing = 12.0; +import 'package:restaurantour/presentation/utils/constants.dart'; class RestaurantDetailPage extends StatelessWidget { const RestaurantDetailPage({ @@ -80,7 +78,7 @@ class RestaurantDetailPage extends StatelessWidget { ), // Display the restaurant details Padding( - padding: const EdgeInsets.all(detailSpacing), + padding: const EdgeInsets.all(Constants.detailSpacing), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -93,40 +91,45 @@ class RestaurantDetailPage extends StatelessWidget { ), ), const Padding( - padding: EdgeInsets.symmetric(horizontal: detailSpacing), + padding: EdgeInsets.symmetric( + horizontal: Constants.detailSpacing, + ), child: Divider( color: Colors.grey, ), ), // Display Address Padding( - padding: const EdgeInsets.all(detailSpacing), + padding: const EdgeInsets.all(Constants.detailSpacing), child: RestaurantAddress( address: restaurant.address, ), ), const Padding( - padding: EdgeInsets.symmetric(horizontal: detailSpacing), + padding: EdgeInsets.symmetric( + horizontal: Constants.detailSpacing), child: Divider( color: Colors.grey, ), ), - // Display the restaurant rating Padding( - padding: const EdgeInsets.all(detailSpacing), + padding: const EdgeInsets.all( + Constants.detailSpacing, + ), child: RestaurantRating( rating: restaurant.rating, ), ), const Padding( - padding: EdgeInsets.symmetric(horizontal: detailSpacing), + padding: EdgeInsets.symmetric( + horizontal: Constants.detailSpacing), child: Divider( color: Colors.grey, ), ), Padding( - padding: const EdgeInsets.all(detailSpacing), + padding: const EdgeInsets.all(Constants.detailSpacing), child: Align( alignment: Alignment.topLeft, child: Text( @@ -134,12 +137,11 @@ class RestaurantDetailPage extends StatelessWidget { ), ), ), - // Display the restaurant reviews Padding( - padding: - const EdgeInsets.symmetric(horizontal: detailSpacing) - .copyWith(bottom: detailSpacing), + padding: const EdgeInsets.symmetric( + horizontal: Constants.detailSpacing, + ), child: Column( children: restaurant.reviews .map( @@ -147,13 +149,15 @@ class RestaurantDetailPage extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ RestaurantStars(rating: restaurant.rating), - const SizedBox(height: detailVerticalSpacing), + const SizedBox( + height: Constants.detailVerticalSpacing), Text( review.comment, maxLines: 3, overflow: TextOverflow.ellipsis, ), - const SizedBox(height: detailVerticalSpacing), + const SizedBox( + height: Constants.detailVerticalSpacing), Row( children: [ CircleAvatar( @@ -167,7 +171,9 @@ class RestaurantDetailPage extends StatelessWidget { Text(review.author.name), ], ), - const SizedBox(height: detailVerticalSpacing), + const SizedBox( + height: Constants.detailVerticalSpacing, + ), const Divider( color: Colors.grey, ), diff --git a/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart b/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart index 5f178f54..714a5996 100644 --- a/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart +++ b/lib/presentation/restaurants/restaurant_list/restaurant_list_page.dart @@ -5,6 +5,7 @@ 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); @@ -15,7 +16,7 @@ class RestaurantListPage extends StatelessWidget { length: 2, child: Scaffold( appBar: AppBar( - title: const Text('Restaurant List'), + title: const Text(Constants.restaurantListTitle), bottom: const TabBar( labelStyle: TextStyle( fontFamily: 'OpenSans', @@ -24,10 +25,10 @@ class RestaurantListPage extends StatelessWidget { labelColor: Colors.black, tabs: [ Tab( - text: 'All Restaurants', + text: Constants.allRestaurantsTabTitle, ), Tab( - text: 'My Favorites', + text: Constants.favoriteRestaurantsTabTitle, ), ], ), @@ -68,7 +69,7 @@ class _AllRestaurantsTab extends StatelessWidget { if (viewModel.hasError) { return const Center( child: Text( - 'Oops, unable to fetch restaurants. Try again later.', + Constants.errorFetching, ), ); } @@ -127,7 +128,7 @@ class _MyFavoritesTab extends StatelessWidget { if (viewModel.hasError) { return const Center( child: Text( - 'Oops, unable to fetch restaurants. Try again later.', + Constants.errorFetching, ), ); } 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/test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart b/test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart deleted file mode 100644 index 8b137891..00000000 --- a/test/domain/restaurants/repositories/repository_impl/restaurant_repository_impl.dart +++ /dev/null @@ -1 +0,0 @@ - diff --git a/test/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart b/test/domain/restaurants/repositories/repository_impl/shared_preferences_repository_impl.dart deleted file mode 100644 index e69de29b..00000000 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/restaurant_list_view_model_test.dart b/test/presentation/restaurants/restaurant_list/restaurant_list_view_model_test.dart similarity index 59% rename from test/presentation/restaurant_list_view_model_test.dart rename to test/presentation/restaurants/restaurant_list/restaurant_list_view_model_test.dart index 64154a19..37fc24cd 100644 --- a/test/presentation/restaurant_list_view_model_test.dart +++ b/test/presentation/restaurants/restaurant_list/restaurant_list_view_model_test.dart @@ -1,8 +1,9 @@ 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'; +import '../../../test_utils/mocks.mocks.dart'; void main() { group('$RestaurantListViewModel', () { @@ -18,6 +19,21 @@ void main() { 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 { @@ -26,11 +42,11 @@ void main() { expect(viewModel.isLoading, true); verify(mockGetRestaurantsUseCase(0)).called(1); verify(mockWatchFavoriteRestaurantsUseCase()).called(1); - }); - test('get restaurants should get more restaurants', () async { - await viewModel.getRestaurants(); - verify(mockGetRestaurantsUseCase(0)).called(1); + await Future.delayed(Duration.zero); + expect(viewModel.isLoading, false); + expect(viewModel.hasData, true); + expect(viewModel.restaurants.length, 1); }); }); } From 23fcdfca8701f46ef6d58f868e9505e7d21e8804 Mon Sep 17 00:00:00 2001 From: Julian Velez Date: Sun, 3 Mar 2024 09:09:51 -0500 Subject: [PATCH 16/16] chore(restaurant-list): restore query limit --- lib/data/sources/yelp_source.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/data/sources/yelp_source.dart b/lib/data/sources/yelp_source.dart index df0e6171..33cd08d3 100644 --- a/lib/data/sources/yelp_source.dart +++ b/lib/data/sources/yelp_source.dart @@ -86,7 +86,7 @@ class YelpSource { String _getQuery(int offset) { return ''' query getRestaurants { - search(location: "Las Vegas", limit: 3, offset: $offset) { + search(location: "Las Vegas", limit: 15, offset: $offset) { total business { id