Skip to content
This repository was archived by the owner on Aug 9, 2024. It is now read-only.

Feat/jackson cuevas test #13

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions lib/common/app_theme.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'package:flutter/material.dart';

final ThemeData lightTheme = ThemeData(
brightness: Brightness.light,
primaryColor: Colors.white,
fontFamily: 'Montserrat',
textTheme: const TextTheme(
displayLarge: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
titleLarge: TextStyle(fontSize: 16.0, fontStyle: FontStyle.italic),
bodyMedium: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
appBarTheme: const AppBarTheme(
color: Colors.white,
elevation: 0,
iconTheme: IconThemeData(color: Colors.black),
titleTextStyle: TextStyle(
color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.bold),
),
tabBarTheme: const TabBarTheme(
labelColor: Colors.black,
unselectedLabelColor: Colors.grey,
indicator: UnderlineTabIndicator(
borderSide: BorderSide(color: Colors.black, width: 2.0),
),
),
cardTheme: CardTheme(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
elevation: 4.0,
margin: const EdgeInsets.all(10.0),
),
);
9 changes: 9 additions & 0 deletions lib/common/constants.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
abstract class Constants {
static const appName = 'RestauranTour';
static const allrestaurants = 'All Restaurant';
static const myFavorites = 'My Favorites';
static const openNow = 'Open Now';
static const closed = 'Closed';
static const address = 'Address';
static const overallRating = 'Overall Rating';
}
33 changes: 33 additions & 0 deletions lib/common/shared_pref_helper.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import '../models/restaurant.dart';

class SharedPreferencesHelper {
static final SharedPreferencesHelper instance = SharedPreferencesHelper._();
static late final SharedPreferences sharedPreferences;

factory SharedPreferencesHelper() => instance;

SharedPreferencesHelper._();

static Future<void> initializeSharedPreference() async {
sharedPreferences = await SharedPreferences.getInstance();
}

Future<void> cacheRestaurants(List<Restaurant> restaurants) async {
String jsonString = jsonEncode(
restaurants.map((restaurant) => restaurant.toJson()).toList());
await sharedPreferences.setString('restaurants', jsonString);
}

Future<List<Restaurant>> getRestaurants() async {
String? jsonString = sharedPreferences.getString('restaurants');
if (jsonString == null) return [];
List<dynamic> jsonResponse = jsonDecode(jsonString);
return jsonResponse
.map((restaurantMap) => Restaurant.fromJson(restaurantMap))
.toList();
}
}
66 changes: 66 additions & 0 deletions lib/common/utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

import '../../../models/restaurant.dart';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


class Utils {
static Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}

static Future<File> get _localFile async {
final path = await _localPath;
return File('$path/favorites.json');
}

static Future<List<Restaurant>> loadFavorites() async {
try {
final file = await _localFile;
if (await file.exists()) {
final contents = await file.readAsString();
final List<dynamic> jsonData = json.decode(contents);
return jsonData.map((item) => Restaurant.fromJson(item)).toList();
}
return [];
} catch (e) {
// Handle the exception, possibly logging or showing a message to the user
return [];
}
}

static Future<void> addFavorite(Restaurant restaurant) async {
final favorites = await loadFavorites();
if (!favorites.any((element) => element.id == restaurant.id)) {
favorites.add(restaurant);
await _saveToFile(favorites);
}
}

static Future<void> removeFavorite(String id) async {
final favorites = await loadFavorites();
favorites.removeWhere((restaurant) => restaurant.id == id);
await _saveToFile(favorites);
}

static Future<void> _saveToFile(List<Restaurant> restaurants) async {
final file = await _localFile;
final String jsonString =
json.encode(restaurants.map((e) => e.toJson()).toList());
await file.writeAsString(jsonString);
}

static Future<void> toggleFavorite(Restaurant restaurant) async {
final favorites = await loadFavorites();
final existingIndex = favorites.indexWhere((r) => r.id == restaurant.id);

if (existingIndex >= 0) {
// Restaurant is already a favorite, remove it
await removeFavorite(restaurant.id!);
} else {
// Restaurant is not a favorite, add it
await addFavorite(restaurant);
}
}
}
18 changes: 13 additions & 5 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:restaurantour/modules/home/views/home_view.dart';
import 'package:restaurantour/repositories/yelp_repository.dart';

void main() {
import 'common/app_theme.dart';
import 'common/shared_pref_helper.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

await SharedPreferencesHelper.initializeSharedPreference();

runApp(const Restaurantour());
}

Expand All @@ -13,10 +23,8 @@ class Restaurantour extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: 'RestauranTour',
theme: ThemeData(
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: const HomePage(),
theme: lightTheme,
home: const HomeView(),
);
}
}
Expand Down
55 changes: 55 additions & 0 deletions lib/modules/home/views/home_view.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
import 'package:restaurantour/common/constants.dart';

import '../../restaurant/views/favorites_restaurants_list_view.dart';
import '../../restaurant/views/restaurants_list_view.dart';

class HomeView extends StatefulWidget {
const HomeView({Key? key}) : super(key: key);

@override
State<HomeView> createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView>
with SingleTickerProviderStateMixin {
late TabController _tabController;

@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 2);
}

@override
void dispose() {
_tabController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(Constants.appName),
bottom: TabBar(
indicatorSize: TabBarIndicatorSize.label,
controller: _tabController,
tabAlignment: TabAlignment.center,
tabs: const [
Tab(
text: Constants.allrestaurants,
),
Tab(
text: Constants.myFavorites,
),
],
),
),
body: TabBarView(
controller: _tabController,
children: const [RestaurantsListView(), FavoritesRestaurantsListView()],
),
);
}
}
41 changes: 41 additions & 0 deletions lib/modules/restaurant/view_models/restaurant_view_model.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:stacked/stacked.dart';

import '../../../common/shared_pref_helper.dart';
import '../../../models/restaurant.dart';
import '../../../repositories/yelp_repository.dart';

class RestaurantViewModel extends BaseViewModel {
final YelpRepository yelpRepo;
final SharedPreferencesHelper sharedPrefHelper =
SharedPreferencesHelper.instance;

List<Restaurant> restaurants = [];
String? errorMessage;

RestaurantViewModel({required this.yelpRepo});

Future<void> ready() async {
setBusy(true);
var cachedRestaurants = await sharedPrefHelper.getRestaurants();
if (cachedRestaurants.isNotEmpty) {
restaurants = cachedRestaurants;
} else {
await fetchAndCacheRestaurants();
}
setBusy(false);
}

Future fetchAndCacheRestaurants() async {
try {
var response = await yelpRepo.getRestaurants();
if (response!.restaurants!.isNotEmpty) {
restaurants = response.restaurants!;
await sharedPrefHelper.cacheRestaurants(restaurants);
}
notifyListeners();
} catch (e) {
errorMessage = e.toString();
notifyListeners();
}
}
}
59 changes: 59 additions & 0 deletions lib/modules/restaurant/views/favorites_restaurants_list_view.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
import 'package:restaurantour/common/utils.dart';

import '../../../models/restaurant.dart';
import '../../../widgets/restaurant_card_widget.dart';
import 'restaurant_detail_view.dart';

class FavoritesRestaurantsListView extends StatelessWidget {
const FavoritesRestaurantsListView({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return FutureBuilder<List<Restaurant>>(
future: Utils.loadFavorites(),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(
child: CircularProgressIndicator(
color: Colors.black,
));
}

if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
var restaurant = snapshot.data![index];
return InkWell(
onTap: () => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RestaurantDetailView(
restaurantIndex: index,
restaurant: restaurant,
),
),
),
},
child: RestaurantCardWidget(
restaurantIndex: index,
restaurant: restaurant,
),
);
},
);
}

if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}

return const Center(
child: Text('Press a button to start fetching data'),
);
},
);
}
}
Loading