Skip to content

Commit

Permalink
실제 DB에서 update 되도록 기능 추가 #14
Browse files Browse the repository at this point in the history
  • Loading branch information
korca0220 committed Mar 17, 2021
1 parent 33ceee9 commit 42a6080
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 26 deletions.
19 changes: 18 additions & 1 deletion shop_app/lib/providers/products.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:html';

import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
Expand Down Expand Up @@ -73,8 +75,23 @@ class Products with ChangeNotifier {
}
}

void updateProduct(String id, Product newProduct) {
Future<void> 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();
Expand Down
46 changes: 21 additions & 25 deletions shop_app/lib/screens/edit_product_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,32 +55,28 @@ class _EditProductScreenState extends State<EditProductScreen> {
_isLoading = true;
});
if (_editedProduct.id != null) {
Provider.of<Products>(context, listen: false)
.updateProduct(_editedProduct.id, _editedProduct);
setState(() {
_isLoading = false;
});
Navigator.of(context).pop();
}
try {
await Provider.of<Products>(context, listen: false)
.addProduct(_editedProduct);
} catch (error) {
return showDialog<Null>(
context: context,
builder: (ctx) => AlertDialog(
title: Text('An Error occurred'),
content: Text('Something went '),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: Text('Okay'))
],
),
);
} finally {
.updateProduct(_editedProduct.id, _editedProduct);
} else {
try {
await Provider.of<Products>(context, listen: false)
.addProduct(_editedProduct);
} catch (error) {
return showDialog<Null>(
context: context,
builder: (ctx) => AlertDialog(
title: Text('An Error occurred'),
content: Text('Something went '),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: Text('Okay'))
],
),
);
}
setState(() {
_isLoading = false;
});
Expand Down

0 comments on commit 42a6080

Please sign in to comment.