Menu
CoddyTech

レシピブック:お気に入り

CoddyのFlutterジャーニー「リストと画面」セクションの一部。レッスン 31/33。

毎週作るレシピがいくつかあります。各行の末尾にあるハートはお気に入りを示します。お気に入りでない場合は空のハート、お気に入りの場合は赤く塗りつぶされたハートです。

レシピがお気に入りかどうかはレシピの一部なので、フィールドになります。他のフィールドとは異なり値が変わるため、finalではなく、初期値はfalseです。

bool favorite = false;

変化するデータにはsetStateが必要なので、HomeScreenはStatefulWidgetになります。レシピはbuildからStateクラスに移します。build内で作成したリストはsetStateのたびに作り直され、ハートがすべて空になってしまうためです。

ハートはIconButtonです。アイコンは? :を使って塗りつぶされたハートか空のハートを選び、押すとフィールドの値が反転します。recipe.favorite = !recipe.favorite。

challenge icon

チャレンジ

難しい

各レシピにお気に入りのハートを追加しましょう。

  • 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});
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

リストと画面のすべてのレッスン

自分で練習してみよう: Flutterオンラインコンパイラ