食谱簿:食谱界面
本课属于 Coddy Flutter 学习旅程的“列表和屏幕”单元。第 29 课,共 33 课。
名字列表只是一个开始,但食谱本是用来做菜的。点击一份食谱,就应该打开它自己的屏幕。
这个屏幕是一个新的组件类 RecipeScreen,它通过构造函数接收食谱。一个类就能显示任意食谱:点击的列表项通过传入自己的 recipe 来决定显示哪一份。
它的应用栏会显示食谱名称,并自动显示返回箭头,因为列表位于它下方的堆栈中。
挑战
中等让每道食谱都能打开自己的页面:
- 编写一个
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});
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
列表和屏幕中的所有课
自己练习: Flutter 在线编译器