Menu
CoddyTech

食谱簿:收藏夹标签页

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

只有在你能再次找到喜欢的食谱时,爱心才有用。第二个标签页 Favorites 只显示带红色爱心的食谱。

两个标签页显示的食谱列表看起来相同,所以把列表只写一次,作为一个接收要显示的食谱的方法:

Widget recipeList(List<Recipe> shown) {
  return ListView.builder(...);
}

收藏的食谱是 favorite 为 true 的食谱。请在 build 的开头计算出它们,这样每次 setState 后,标签页都会显示正确的内容。然后,主体会根据当前标签页显示 recipeList(recipes) 或 recipeList(favorites)。

challenge icon

挑战

困难

为食谱本添加标签页:

  • 将 ListView.builder 移到方法 Widget recipeList(List<Recipe> shown) 中,用来列出 shown
  • 添加一个包含两个标签页的 NavigationBar:Recipes(Icons.menu_book_outlined,选中时使用 Icons.menu_book)和 Favorites(Icons.star_border,选中时使用 Icons.star),并将标签页的 index 保存在状态中
  • Recipes 标签页列出所有食谱,Favorites 标签页只列出收藏的食谱

亲手试试

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

  @override
  Widget build(BuildContext context) {
    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)),
              );
            },
            trailing: IconButton(
              icon: Icon(
                recipe.favorite ? Icons.favorite : Icons.favorite_border,
                color: recipe.favorite ? Colors.red : null,
              ),
              onPressed: () {
                setState(() {
                  recipe.favorite = !recipe.favorite;
                });
              },
            ),
          );
        },
      ),
    );
  }
}

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 在线编译器