Menu
CoddyTech

レシピブック:レシピ画面

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

名前の一覧は出発点ですが、レシピブックは料理をするためのものです。レシピをタップすると、そのレシピ専用の画面が開くようにしましょう。

その画面は新しいウィジェットクラスRecipeScreenで、コンストラクターを通じてレシピを受け取ります。1つのクラスでどのレシピも表示できます。どのレシピを表示するかは、タップされたタイルが画面を表示するときにrecipeを渡して決めます。

アプリバーにはレシピ名が表示されます。また、リストがスタックの下にあるため、戻る矢印も自動的に表示されます。

challenge icon

チャレンジ

中級

各レシピをそれぞれ独自の画面で開けるようにします。

  • RecipeScreen ウィジェットを作成し、final Recipe recipe; フィールドと required this.recipe パラメーターを追加します。
  • アプリバーにはレシピ名を表示し、本文には(レシピの所要時間を使って)Ready in 20 minutes をフォントサイズ18で表示し、16ピクセルのパディングを設定します。
  • タイルをタップすると RecipeScreen(recipe: recipe) に遷移します。

自分で試してみよう

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'),
          );
        },
      ),
    );
  }
}

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オンラインコンパイラ