Menu
CoddyTech

Sổ tay công thức nấu ăn: Màn hình công thức

Thuộc phần Danh sách và màn hình trong hành trình Flutter của Coddy. Bài học 29 trên 33.

Danh sách tên chỉ là bước khởi đầu, còn sách công thức là để nấu ăn. Khi chạm vào một công thức, màn hình riêng của công thức đó sẽ mở ra.

Màn hình đó là một lớp widget mới, RecipeScreen, nhận công thức thông qua hàm khởi tạo. Một lớp có thể hiển thị bất kỳ công thức nào: ô được chạm vào sẽ quyết định công thức nào bằng cách truyền recipe khi mở màn hình.

Thanh ứng dụng hiển thị tên công thức và tự có mũi tên quay lại, vì danh sách nằm bên dưới nó trong ngăn xếp.

challenge icon

Thử thách

Trung bình

Để mỗi công thức mở một màn hình riêng:

  • viết một tiện ích RecipeScreen có trường final Recipe recipe; và tham số required this.recipe
  • thanh ứng dụng hiển thị tên công thức, còn phần thân hiển thị Ready in 20 minutes (với số phút của công thức), cỡ chữ 18 và khoảng đệm 16 pixel
  • khi nhấn vào một mục, mở RecipeScreen(recipe: recipe)

Tự làm thử

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

class Recipe {
  final String name;
  final int minutes;
  final List<String> ingredients;

  Recipe({required this.name, required this.minutes, required this.ingredients});
}
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Danh sách và màn hình

Tự luyện tập: Trình biên dịch Flutter online