Menu
CoddyTech

食谱簿:食材

本课属于 Coddy Flutter 学习旅程的“列表和屏幕”单元。第 30 课,共 33 课。

食谱页面需要展示你想看的内容:食材。每份食谱都已将食材放在自己的 ingredients 列表中。

页面也会变成一个列表:时间、标题,然后每种食材占一行。带有 padding: 的 ListView 可以容纳所有内容,而且当食谱有 20 种食材时,仍然可以滚动。通过遍历 recipe.ingredients 的集合 for 来生成这些行。

加粗并增大字号后,Ingredients 看起来就像一个标题,让你一眼就能找到列表。

challenge icon

挑战

简单

在食谱页面显示配料。将页面主体设为带有 16 像素内边距的 ListView,其中包含:

  • 和之前一样的 Ready in 文本
  • 一个高度为 24 的 SizedBox,然后是大小为 20 且加粗的标题 Ingredients
  • 每种配料对应一个 ListTile,并将 Icons.check_circle_outline 设为其 leading:

亲手试试

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});
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

列表和屏幕中的所有课

自己练习: Flutter 在线编译器