Menu
CoddyTech

Книга рецептов: избранное

Часть раздела Списки и экраны путешествия по Flutter на Coddy. Урок 31 из 33.

Некоторые блюда вы готовите каждую неделю. Сердечко в конце каждой строки отмечает избранное: пустое сердечко, если блюдо не в избранном, и красное заполненное — если в избранном.

Информация о том, входит ли блюдо в избранное, относится к самому блюду, поэтому она становится полем. В отличие от остальных, это поле меняется, поэтому оно не final, а его начальное значение — false:

bool favorite = false;

Для изменяемых данных нужен setState, поэтому HomeScreen становится StatefulWidget. Рецепты перемещаются из build в класс State: список, созданный внутри build, создаётся заново при каждом вызове setState, и все сердечки становились бы пустыми.

Сердечко — это IconButton. Его значок выбирает заполненное или пустое сердечко с помощью ? :, а при нажатии значение поля переключается: recipe.favorite = !recipe.favorite.

challenge icon

Задание

Сложно

Добавьте сердце избранного к каждому рецепту:

  • добавьте в Recipe поле bool favorite = false;
  • преобразуйте HomeScreen в StatefulWidget и переместите список рецептов в его класс State
  • добавьте к каждой плитке trailing: IconButton, показывающий Icons.favorite_border, или красный Icons.favorite, если рецепт добавлен в избранное. Нажатие переключает значение favorite

Попробуйте сами

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: 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;

  Recipe({required this.name, required this.minutes, required this.ingredients});
}
quiz iconПроверьте себя

В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.

Все уроки раздела Списки и экраны

Потренируйтесь самостоятельно: Онлайн-компилятор Flutter