Skip to content

Commit 42a6080

Browse files
committed
실제 DB에서 update 되도록 기능 추가 #14
1 parent 33ceee9 commit 42a6080

File tree

2 files changed

+39
-26
lines changed

2 files changed

+39
-26
lines changed

shop_app/lib/providers/products.dart

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import 'dart:html';
2+
13
import 'package:flutter/foundation.dart';
24
import 'dart:convert';
35
import 'package:http/http.dart' as http;
@@ -73,8 +75,23 @@ class Products with ChangeNotifier {
7375
}
7476
}
7577

76-
void updateProduct(String id, Product newProduct) {
78+
Future<void> updateProduct(String id, Product newProduct) async {
7779
final prodIndex = _items.indexWhere((element) => element.id == id);
80+
if (prodIndex > 0) {
81+
final url =
82+
'https://flutter-shop-app-c87f7-default-rtdb.firebaseio.com/products/$id.json';
83+
await http.patch(
84+
Uri.parse(url),
85+
body: json.encode(
86+
{
87+
'title': newProduct.title,
88+
'description': newProduct.description,
89+
'price': newProduct.price,
90+
'imageUrl': newProduct.imageUrl,
91+
},
92+
),
93+
);
94+
}
7895
if (prodIndex >= 0) {
7996
_items[prodIndex] = newProduct;
8097
notifyListeners();

shop_app/lib/screens/edit_product_screen.dart

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -55,32 +55,28 @@ class _EditProductScreenState extends State<EditProductScreen> {
5555
_isLoading = true;
5656
});
5757
if (_editedProduct.id != null) {
58-
Provider.of<Products>(context, listen: false)
59-
.updateProduct(_editedProduct.id, _editedProduct);
60-
setState(() {
61-
_isLoading = false;
62-
});
63-
Navigator.of(context).pop();
64-
}
65-
try {
6658
await Provider.of<Products>(context, listen: false)
67-
.addProduct(_editedProduct);
68-
} catch (error) {
69-
return showDialog<Null>(
70-
context: context,
71-
builder: (ctx) => AlertDialog(
72-
title: Text('An Error occurred'),
73-
content: Text('Something went '),
74-
actions: <Widget>[
75-
TextButton(
76-
onPressed: () {
77-
Navigator.of(ctx).pop();
78-
},
79-
child: Text('Okay'))
80-
],
81-
),
82-
);
83-
} finally {
59+
.updateProduct(_editedProduct.id, _editedProduct);
60+
} else {
61+
try {
62+
await Provider.of<Products>(context, listen: false)
63+
.addProduct(_editedProduct);
64+
} catch (error) {
65+
return showDialog<Null>(
66+
context: context,
67+
builder: (ctx) => AlertDialog(
68+
title: Text('An Error occurred'),
69+
content: Text('Something went '),
70+
actions: <Widget>[
71+
TextButton(
72+
onPressed: () {
73+
Navigator.of(ctx).pop();
74+
},
75+
child: Text('Okay'))
76+
],
77+
),
78+
);
79+
}
8480
setState(() {
8581
_isLoading = false;
8682
});

0 commit comments

Comments
 (0)