diff --git a/shop_app/lib/providers/products.dart b/shop_app/lib/providers/products.dart index 4fd0475..fa162c5 100644 --- a/shop_app/lib/providers/products.dart +++ b/shop_app/lib/providers/products.dart @@ -1,3 +1,5 @@ +import 'dart:html'; + import 'package:flutter/foundation.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; @@ -73,8 +75,23 @@ class Products with ChangeNotifier { } } - void updateProduct(String id, Product newProduct) { + Future updateProduct(String id, Product newProduct) async { final prodIndex = _items.indexWhere((element) => element.id == id); + if (prodIndex > 0) { + final url = + 'https://flutter-shop-app-c87f7-default-rtdb.firebaseio.com/products/$id.json'; + await http.patch( + Uri.parse(url), + body: json.encode( + { + 'title': newProduct.title, + 'description': newProduct.description, + 'price': newProduct.price, + 'imageUrl': newProduct.imageUrl, + }, + ), + ); + } if (prodIndex >= 0) { _items[prodIndex] = newProduct; notifyListeners(); diff --git a/shop_app/lib/screens/edit_product_screen.dart b/shop_app/lib/screens/edit_product_screen.dart index 50479d6..9ed40f3 100644 --- a/shop_app/lib/screens/edit_product_screen.dart +++ b/shop_app/lib/screens/edit_product_screen.dart @@ -55,32 +55,28 @@ class _EditProductScreenState extends State { _isLoading = true; }); if (_editedProduct.id != null) { - Provider.of(context, listen: false) - .updateProduct(_editedProduct.id, _editedProduct); - setState(() { - _isLoading = false; - }); - Navigator.of(context).pop(); - } - try { await Provider.of(context, listen: false) - .addProduct(_editedProduct); - } catch (error) { - return showDialog( - context: context, - builder: (ctx) => AlertDialog( - title: Text('An Error occurred'), - content: Text('Something went '), - actions: [ - TextButton( - onPressed: () { - Navigator.of(ctx).pop(); - }, - child: Text('Okay')) - ], - ), - ); - } finally { + .updateProduct(_editedProduct.id, _editedProduct); + } else { + try { + await Provider.of(context, listen: false) + .addProduct(_editedProduct); + } catch (error) { + return showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text('An Error occurred'), + content: Text('Something went '), + actions: [ + TextButton( + onPressed: () { + Navigator.of(ctx).pop(); + }, + child: Text('Okay')) + ], + ), + ); + } setState(() { _isLoading = false; });