Menu
CoddyTech

Книга рецептов: ингредиенты

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

На экране рецепта нужно то, ради чего вы пришли: ингредиенты. В каждом рецепте они уже содержатся в списке ingredients.

Экран тоже становится списком: время, заголовок, затем по одной строке на каждый ингредиент. ListView с padding: содержит их все и при этом прокручивается, если в рецепте двадцать ингредиентов. Строки создаёт конструкция for для коллекций, перебирающая recipe.ingredients.

Жирное начертание и увеличенный размер шрифта помогают воспринимать Ingredients как заголовок, поэтому взгляд сразу находит список.

challenge icon

Задание

Легко

Покажи ингредиенты на экране рецепта. Сделай его body виджетом ListView с отступом 16 пикселей, содержащим:

  • текст Ready in, как и раньше
  • SizedBox высотой 24, затем заголовок Ingredients размером 20 и полужирным шрифтом
  • по одному 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