← Назад к вопросам

Приведи пример использования Scaffold

1.0 Junior🔥 191 комментариев
#Dart#Flutter виджеты

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI26 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Использование Scaffold в Flutter

Scaffold — это один из самых важных компонентов Material Design в Flutter. Это контейнер, который предоставляет основную структуру для экрана приложения, включая AppBar, BottomNavigationBar, FloatingActionButton и другие элементы UI.

Что такое Scaffold?

Scaffold — это материальный контейнер, который реализует базовый макет Material Design. Он позволяет:

  • Добавлять AppBar в верхней части экрана
  • Содержать основное содержимое в body
  • Добавлять FloatingActionButton для основного действия
  • Реализовать BottomNavigationBar для навигации
  • Показывать SnackBar и Dialog
  • Управлять Drawer для бокового меню

Практический пример

import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _selectedIndex = 0;

  final List<Widget> _screens = [
    const HomeScreen(),
    const SearchScreen(),
    const ProfileScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('My App'),
          backgroundColor: Colors.blue,
          elevation: 4.0,
          actions: [
            IconButton(
              icon: const Icon(Icons.notifications),
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Notifications opened')),
                );
              },
            ),
          ],
        ),
        body: _screens[_selectedIndex],
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            print('FAB pressed');
          },
          backgroundColor: Colors.blue,
          child: const Icon(Icons.add),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        drawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              const DrawerHeader(
                decoration: BoxDecoration(color: Colors.blue),
                child: Text('Menu'),
              ),
              ListTile(
                title: const Text('Home'),
                onTap: () => Navigator.pop(context),
              ),
              ListTile(
                title: const Text('Settings'),
                onTap: () => Navigator.pop(context),
              ),
            ],
          ),
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          onTap: (index) {
            setState(() => _selectedIndex = index);
          },
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.search),
              label: 'Search',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Profile',
            ),
          ],
        ),
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text('Home Screen'),
    );
  }
}

class SearchScreen extends StatelessWidget {
  const SearchScreen();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text('Search Screen'),
    );
  }
}

class ProfileScreen extends StatelessWidget {
  const ProfileScreen();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text('Profile Screen'),
    );
  }
}

Основные свойства Scaffold

appBar — верхняя панель приложения с заголовком, кнопками действий

body — основной контент экрана, обычно это Column, ListView или другой контейнер

floatingActionButton — плавающая кнопка для основного действия

floatingActionButtonLocation — позиция FAB (centerDocked, centerFloat, endFloat и т.д.)

bottomNavigationBar — навигационная панель в нижней части

drawer — боковое меню, открывается свайпом или через иконку в AppBar

backgroundColor — фон за пределами safe area

Лучшие практики

  • Используй ScaffoldMessenger для SnackBar вместо Scaffold.of(context).showSnackBar
  • Всегда предоставляй label для BottomNavigationBar items для accessibility
  • Используй resizeToAvoidBottomInset: false, если клавиатура не должна сдвигать контент
  • Для сложных макетов можно вложить несколько Scaffold'ов (например, один для основной структуры, другой для деталей)
Приведи пример использования Scaffold | PrepBro