Skip to content

Commit

Permalink
copying final version lib
Browse files Browse the repository at this point in the history
  • Loading branch information
MehdiJarraya committed Aug 15, 2021
1 parent ed4bae3 commit c4e49ab
Show file tree
Hide file tree
Showing 26 changed files with 1,620 additions and 121 deletions.
19 changes: 19 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "shop_http",
"request": "launch",
"type": "dart"
},
{
"name": "shop_http (profile mode)",
"request": "launch",
"type": "dart",
"flutterMode": "profile"
}
]
}
Binary file added README-HOW-TO-USE.pdf
Binary file not shown.
Binary file added assets/fonts/Anton-Regular.ttf
Binary file not shown.
Binary file added assets/fonts/Lato-Bold.ttf
Binary file not shown.
Binary file added assets/fonts/Lato-Regular.ttf
Binary file not shown.
141 changes: 38 additions & 103 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,113 +1,48 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);

// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
import './screens/cart_screen.dart';
import './screens/products_overview_screen.dart';
import './screens/product_detail_screen.dart';
import './providers/products.dart';
import './providers/cart.dart';
import './providers/orders.dart';
import './screens/orders_screen.dart';
import './screens/user_products_screen.dart';
import './screens/edit_product_screen.dart';

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
return MultiProvider(
providers: [
ChangeNotifierProvider.value(
value: Products(),
),
ChangeNotifierProvider.value(
value: Cart(),
),
ChangeNotifierProvider.value(
value: Orders(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
],
child: MaterialApp(
title: 'MyShop',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.deepOrange,
fontFamily: 'Lato',
),
home: ProductsOverviewScreen(),
routes: {
ProductDetailScreen.routeName: (ctx) => ProductDetailScreen(),
CartScreen.routeName: (ctx) => CartScreen(),
OrdersScreen.routeName: (ctx) => OrdersScreen(),
UserProductsScreen.routeName: (ctx) => UserProductsScreen(),
EditProductScreen.routeName: (ctx) => EditProductScreen(),
}),
);
}
}
11 changes: 11 additions & 0 deletions lib/models/http_exception.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class HttpException implements Exception {
final String message;

HttpException(this.message);

@override
String toString() {
return message;
// return super.toString(); // Instance of HttpException
}
}
94 changes: 94 additions & 0 deletions lib/providers/cart.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import 'package:flutter/foundation.dart';

class CartItem {
final String id;
final String title;
final int quantity;
final double price;

CartItem({
@required this.id,
@required this.title,
@required this.quantity,
@required this.price,
});
}

class Cart with ChangeNotifier {
Map<String, CartItem> _items = {};

Map<String, CartItem> get items {
return {..._items};
}

int get itemCount {
return _items.length;
}

double get totalAmount {
var total = 0.0;
_items.forEach((key, cartItem) {
total += cartItem.price * cartItem.quantity;
});
return total;
}

void addItem(
String productId,
double price,
String title,
) {
if (_items.containsKey(productId)) {
// change quantity...
_items.update(
productId,
(existingCartItem) => CartItem(
id: existingCartItem.id,
title: existingCartItem.title,
price: existingCartItem.price,
quantity: existingCartItem.quantity + 1,
),
);
} else {
_items.putIfAbsent(
productId,
() => CartItem(
id: DateTime.now().toString(),
title: title,
price: price,
quantity: 1,
),
);
}
notifyListeners();
}

void removeItem(String productId) {
_items.remove(productId);
notifyListeners();
}

void removeSingleItem(String productId) {
if (!_items.containsKey(productId)) {
return;
}
if (_items[productId].quantity > 1) {
_items.update(
productId,
(existingCartItem) => CartItem(
id: existingCartItem.id,
title: existingCartItem.title,
price: existingCartItem.price,
quantity: existingCartItem.quantity - 1,
));
} else {
_items.remove(productId);
}
notifyListeners();
}

void clear() {
_items = {};
notifyListeners();
}
}
89 changes: 89 additions & 0 deletions lib/providers/orders.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

import './cart.dart';

class OrderItem {
final String id;
final double amount;
final List<CartItem> products;
final DateTime dateTime;

OrderItem({
@required this.id,
@required this.amount,
@required this.products,
@required this.dateTime,
});
}

class Orders with ChangeNotifier {
List<OrderItem> _orders = [];

List<OrderItem> get orders {
return [..._orders];
}

Future<void> fetchAndSetOrders() async {
final url = Uri.https('flutter-update.firebaseio.com', '/orders.json');
final response = await http.get(url);
final List<OrderItem> loadedOrders = [];
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
extractedData.forEach((orderId, orderData) {
loadedOrders.add(
OrderItem(
id: orderId,
amount: orderData['amount'],
dateTime: DateTime.parse(orderData['dateTime']),
products: (orderData['products'] as List<dynamic>)
.map(
(item) => CartItem(
id: item['id'],
price: item['price'],
quantity: item['quantity'],
title: item['title'],
),
)
.toList(),
),
);
});
_orders = loadedOrders.reversed.toList();
notifyListeners();
}

Future<void> addOrder(List<CartItem> cartProducts, double total) async {
final url = Uri.https('flutter-update.firebaseio.com', '/orders.json');
final timestamp = DateTime.now();
final response = await http.post(
url,
body: json.encode({
'amount': total,
'dateTime': timestamp.toIso8601String(),
'products': cartProducts
.map((cp) => {
'id': cp.id,
'title': cp.title,
'quantity': cp.quantity,
'price': cp.price,
})
.toList(),
}),
);
_orders.insert(
0,
OrderItem(
id: json.decode(response.body)['name'],
amount: total,
dateTime: timestamp,
products: cartProducts,
),
);
notifyListeners();
}
}
Loading

0 comments on commit c4e49ab

Please sign in to comment.