1. 기존에 중복 요청한게 있었다.
new_item 화면에서 post로 값을 받은거를 response로 저장해둔거 1회, grocery_list화면에서 get으로 받은거 2회 중복
이를 new_item에서 받은 body값을 pop을 통해 grocery_list로 전달해줌으로써 중복을 제거하자.
- new_item.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shopping_list/data/categories.dart';
import 'package:shopping_list/models/category.dart';
import 'package:shopping_list/models/grocery_item.dart';
class NewItem extends StatefulWidget {
const NewItem({super.key});
@override
State<NewItem> createState() {
return _NewItemState();
}
}
class _NewItemState extends State<NewItem> {
final _formKey = GlobalKey<FormState>();
var _enteredName = '';
var _enteredQuantity = 1;
var _selectedCategory = categories[Categories.vegetables]!;
void _saveItem() async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
final url = Uri.https('flutter-study-1acb3-default-rtdb.firebaseio.com',
'shopping-list.json');
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
},
body: json.encode(
{
'name': _enteredName,
'quantity': _enteredQuantity,
'category': _selectedCategory.title,
},
),
);
final Map<String, dynamic> resData = json.decode(response.body);
if (!context.mounted) {
return;
}
Navigator.of(context).pop(
GroceryItem(
id: resData['name'],
name: _enteredName,
quantity: _enteredQuantity,
category: _selectedCategory,
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add a new item'),
),
body: Padding(
padding: const EdgeInsets.all(12),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
maxLength: 50,
decoration: const InputDecoration(
label: Text('Name'),
),
validator: (value) {
if (value == null ||
value.isEmpty ||
value.trim().length <= 1 ||
value.trim().length > 50) {
return 'Must be between 1 and 50 characters.';
}
return null;
},
onSaved: (value) {
// if (value == null) {
// return;
// }
_enteredName = value!;
},
), // instead of TextField()
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Expanded(
child: TextFormField(
decoration: const InputDecoration(
label: Text('Quantity'),
),
keyboardType: TextInputType.number,
initialValue: _enteredQuantity.toString(),
validator: (value) {
if (value == null ||
value.isEmpty ||
int.tryParse(value) == null ||
int.tryParse(value)! <= 0) {
return 'Must be a valid, positive number.';
}
return null;
},
onSaved: (value) {
_enteredQuantity = int.parse(value!);
},
),
),
const SizedBox(width: 8),
Expanded(
child: DropdownButtonFormField(
value: _selectedCategory,
items: [
for (final category in categories.entries)
DropdownMenuItem(
value: category.value,
child: Row(
children: [
Container(
width: 16,
height: 16,
color: category.value.color,
),
const SizedBox(width: 6),
Text(category.value.title),
],
),
),
],
onChanged: (value) {
setState(() {
_selectedCategory = value!;
});
},
),
),
],
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
_formKey.currentState!.reset();
},
child: const Text('Reset'),
),
ElevatedButton(
onPressed: _saveItem,
child: const Text('Add Item'),
)
],
),
],
),
),
),
);
}
}
- grocery_list.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shopping_list/data/categories.dart';
import 'package:shopping_list/models/grocery_item.dart';
import 'package:shopping_list/widgets/new_item.dart';
class GroceryList extends StatefulWidget {
const GroceryList({super.key});
@override
State<GroceryList> createState() => _GroceryListState();
}
class _GroceryListState extends State<GroceryList> {
List<GroceryItem> _groceryItems = [];
@override
void initState() {
super.initState();
_loadItems();
}
void _loadItems() async {
final url = Uri.https(
'flutter-prep-default-rtdb.firebaseio.com', 'shopping-list.json');
final response = await http.get(url);
final Map<String, dynamic> listData = json.decode(response.body);
final List<GroceryItem> loadedItems = [];
for (final item in listData.entries) {
final category = categories.entries
.firstWhere(
(catItem) => catItem.value.title == item.value['category'])
.value;
loadedItems.add(
GroceryItem(
id: item.key,
name: item.value['name'],
quantity: item.value['quantity'],
category: category,
),
);
}
setState(() {
_groceryItems = loadedItems;
});
}
void _addItem() async {
final newItem = await Navigator.of(context).push<GroceryItem>(
MaterialPageRoute(
builder: (ctx) => const NewItem(),
),
);
if (newItem == null) {
return;
}
setState(() {
_groceryItems.add(newItem);
});
}
void _removeItem(GroceryItem item) {
setState(() {
_groceryItems.remove(item);
});
}
@override
Widget build(BuildContext context) {
Widget content = const Center(child: Text('No items added yet.'));
if (_groceryItems.isNotEmpty) {
content = ListView.builder(
itemCount: _groceryItems.length,
itemBuilder: (ctx, index) => Dismissible(
onDismissed: (direction) {
_removeItem(_groceryItems[index]);
},
key: ValueKey(_groceryItems[index].id),
child: ListTile(
title: Text(_groceryItems[index].name),
leading: Container(
width: 24,
height: 24,
color: _groceryItems[index].category.color,
),
trailing: Text(
_groceryItems[index].quantity.toString(),
),
),
),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Your Groceries'),
actions: [
IconButton(
onPressed: _addItem,
icon: const Icon(Icons.add),
),
],
),
body: content,
);
}
}
1) void _addItem() async {
final newItem = await Navigator.of(context).push<GroceryItem>(
MaterialPageRoute(
builder: (ctx) => const NewItem(),
),
);
if (newItem == null) {
return;
}
setState(() {
_groceryItems.add(newItem);
});
}
--> 다시 async await를 통해 값을 받아오고 setState부분을 통해 값을 넣는다.
'코딩강의 > shopping_list(플러터-유데미)' 카테고리의 다른 글
226. Error Response Handling (0) | 2023.11.15 |
---|---|
225. Managing the Loading State (0) | 2023.11.15 |
~223. Fetching & Transforming Data (0) | 2023.11.15 |
~221. Sending a POST Request to the Backend (0) | 2023.11.15 |
~214. Final Challenge Solution (0) | 2023.11.14 |