Menu
CoddyTech

レシピブック:お気に入りはまだありません

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

お気に入りに何かを追加する前に、お気に入りタブを開いてみましょう。画面は空白で、空白の画面は壊れているように見えます。リストが空の場合は、なぜ空なのかを表示する必要があります。

リストのisEmptyは、項目がないときにtrueになります。returnの前に、ifを使ってbuild内で表示するページを選びます。

Widget page;
if (index == 0) {
  page = recipeList(recipes);
} else if (favorites.isEmpty) {
  page = const Center(child: Text('No favorites yet'));
} else {
  page = recipeList(favorites);
}

Widget型の変数には任意のウィジェットを格納できるため、pageは一方の分岐ではリストになり、もう一方の分岐ではメッセージになります。その後、Scaffoldのbodyはpageになります。

challenge icon

チャレンジ

簡単

お気に入りタブに表示するものがない場合は、空のリストの代わりに画面中央にサイズ18でNo favorites yetを表示します。レシピをお気に入りにすると、タブに再び表示されます。

自分で試してみよう

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 StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  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']),
  ];
  int index = 0;

  Widget recipeList(List<Recipe> shown) {
    return ListView.builder(
      itemCount: shown.length,
      itemBuilder: (context, i) {
        final Recipe recipe = shown[i];
        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)),
            );
          },
          trailing: IconButton(
            icon: Icon(
              recipe.favorite ? Icons.favorite : Icons.favorite_border,
              color: recipe.favorite ? Colors.red : null,
            ),
            onPressed: () {
              setState(() {
                recipe.favorite = !recipe.favorite;
              });
            },
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final List<Recipe> favorites = recipes.where((recipe) => recipe.favorite).toList();
    return Scaffold(
      appBar: AppBar(title: const Text('Recipe Book')),
      body: index == 0 ? recipeList(recipes) : recipeList(favorites),
      bottomNavigationBar: NavigationBar(
        selectedIndex: index,
        onDestinationSelected: (int i) {
          setState(() {
            index = i;
          });
        },
        destinations: const [
          NavigationDestination(
            icon: Icon(Icons.menu_book_outlined),
            selectedIcon: Icon(Icons.menu_book),
            label: 'Recipes',
          ),
          NavigationDestination(
            icon: Icon(Icons.star_border),
            selectedIcon: Icon(Icons.star),
            label: 'Favorites',
          ),
        ],
      ),
    );
  }
}

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;
  bool favorite = false;

  Recipe({required this.name, required this.minutes, required this.ingredients});
}
quiz icon腕試し

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

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

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