Книга рецептов: вкладка «Избранное»
Часть раздела Списки и экраны путешествия по Flutter на Coddy. Урок 32 из 33.
Сердца полезны только в том случае, если ты можешь снова найти избранные рецепты. На второй вкладке, Favorites, отображаются только рецепты с красным сердцем.
На обеих вкладках отображается одинаковый список рецептов, поэтому напиши список один раз — в виде метода, который принимает рецепты для отображения:
Widget recipeList(List<Recipe> shown) {
return ListView.builder(...);
}В избранное входят рецепты, where favorite которых равно true. Вычисли их в начале build, чтобы список на вкладке обновлялся после каждого вызова setState. Затем в теле отображается recipeList(recipes) или recipeList(favorites) — в зависимости от выбранной вкладки.
Задание
СложноДобавь вкладки в книгу рецептов:
- перемести
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});
}
В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.
Все уроки раздела Списки и экраны
1Прокручиваемые списки
Список с прокруткойЭлементы спискаНачало и конецНажатие на элемент спискаРазделители между строками4Ваши собственные классы
Класс для ваших данныхИменованные и обязательные параметрыПоля, которые могут быть пустымиВиджеты из данных с помощью mapФильтрация списка с помощью whereПоиск в Map7Проект: Книга рецептов
Книга рецептов: список рецептовКнига рецептов: экран рецепта6Вкладки, боковые панели и свайпы
Вкладки с панелью навигацииЗаливные значки для открытой вкладкиБоковая панельУдаление свайпомОтмена свайпаПотренируйтесь самостоятельно: Онлайн-компилятор Flutter