레시피 북: 즐겨찾기
Coddy Flutter 여정의 목록과 화면 섹션에 포함된 레슨. 33개 중 31번째.
매주 만드는 레시피가 있습니다. 각 행 끝에 있는 하트는 즐겨찾기를 표시합니다. 즐겨찾기가 아니면 빈 하트, 즐겨찾기이면 빨간색으로 채워진 하트입니다.
레시피가 즐겨찾기인지 여부는 레시피의 일부이므로 필드가 됩니다. 다른 필드와 달리 값이 바뀌므로 final이 아니며, 처음에는 false로 설정합니다.
bool favorite = false;변경되는 데이터에는 setState가 필요하므로 HomeScreen은 StatefulWidget이 됩니다. 레시피는 build에서 State 클래스로 옮깁니다. build 안에서 만드는 목록은 setState가 호출될 때마다 다시 만들어지기 때문에 모든 하트가 빈 상태로 돌아갑니다.
하트는 IconButton입니다. 아이콘은 ? :를 사용해 채워진 하트 또는 빈 하트를 선택하고, 누르면 필드의 값을 뒤집습니다. recipe.favorite = !recipe.favorite.
챌린지
어려움모든 레시피에 즐겨찾기 하트를 추가하세요:
Recipe에bool favorite = false;필드를 추가하세요HomeScreen을StatefulWidget으로 바꾸고 레시피 목록을 해당State클래스로 옮기세요- 각 타일에
trailing:IconButton을 추가하여Icons.favorite_border를 표시하거나, 레시피가 즐겨찾기인 경우 빨간색Icons.favorite를 표시하세요. 버튼을 누르면favorite값이 반전됩니다
직접 해보기
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final List<Recipe> recipes = [
Recipe(name: 'Pancakes', minutes: 20, ingredients: ['Flour', 'Eggs', 'Milk', 'Butter']),
Recipe(name: 'Tomato Soup', minutes: 35, ingredients: ['Tomatoes', 'Onion', 'Garlic', 'Olive oil']),
Recipe(name: 'Guacamole', minutes: 10, ingredients: ['Avocados', 'Lime', 'Onion', 'Salt']),
Recipe(name: 'Fried Rice', minutes: 25, ingredients: ['Rice', 'Eggs', 'Peas', 'Soy sauce']),
];
return Scaffold(
appBar: AppBar(title: const Text('Recipe Book')),
body: ListView.builder(
itemCount: recipes.length,
itemBuilder: (context, index) {
final Recipe recipe = recipes[index];
return ListTile(
leading: const Icon(Icons.restaurant_menu),
title: Text(recipe.name),
subtitle: Text('${recipe.minutes} min'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => RecipeScreen(recipe: recipe)),
);
},
);
},
),
);
}
}
class RecipeScreen extends StatelessWidget {
const RecipeScreen({super.key, required this.recipe});
final Recipe recipe;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(recipe.name)),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Text('Ready in ${recipe.minutes} minutes', style: const TextStyle(fontSize: 18)),
const SizedBox(height: 24),
const Text('Ingredients', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
for (String ingredient in recipe.ingredients)
ListTile(
leading: const Icon(Icons.check_circle_outline),
title: Text(ingredient),
),
],
),
);
}
}
class Recipe {
final String name;
final int minutes;
final List<String> ingredients;
Recipe({required this.name, required this.minutes, required this.ingredients});
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
목록과 화면의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러