レシピブック:材料
CoddyのFlutterジャーニー「リストと画面」セクションの一部。レッスン 30/33。
レシピ画面で必要なのは、あなたが見に来たもの、つまり材料です。各レシピには、すでにingredientsリストに材料が含まれています。
画面もリストになります。時間、見出し、そして材料ごとに1行です。padding:を指定したListViewにすべてを収めれば、材料が20個あるレシピでもスクロールできます。recipe.ingredientsを対象にしたコレクションforで各行を作ります。
太字で文字を大きくすると、Ingredientsが見出しとして認識され、リストがすぐに目に入ります。
チャレンジ
簡単レシピ画面に材料を表示します。本文をパディング16ピクセルのListViewにし、次の内容を含めます。
- 前と同じ
Ready inのテキスト - 高さ24の
SizedBox、続いてサイズ20で太字の見出しIngredients - 材料ごとに1つの
ListTileを配置し、そのleading:にはIcons.check_circle_outlineを指定します
自分で試してみよう
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: Padding(
padding: const EdgeInsets.all(16),
child: Text('Ready in ${recipe.minutes} minutes', style: const TextStyle(fontSize: 18)),
),
);
}
}
class Recipe {
final String name;
final int minutes;
final List<String> ingredients;
Recipe({required this.name, required this.minutes, required this.ingredients});
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
リストと画面のすべてのレッスン
自分で練習してみよう: Flutterオンラインコンパイラ