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

Какие знаешь виды виджетов?

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

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

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

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

Виды виджетов в Flutter

Виджет — это базовая строительная единица Flutter приложения. Каждый элемент UI (кнопка, текст, картинка) — это виджет. Flutter имеет сотни встроенных виджетов, разделённых на категории.

1. Stateless vs Stateful

StatelessWidget — виджет без состояния, неизменяемый:

class MyButton extends StatelessWidget {
  const MyButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => print('Clicked'),
      child: Text('Press me'),
    );
  }
}

StatefulWidget — виджет со состоянием, может меняться:

class Counter extends StatefulWidget {
  const Counter({Key? key}) : super(key: key);

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $count'),
        ElevatedButton(
          onPressed: () => setState(() => count++),
          child: Text('Increment'),
        ),
      ],
    );
  }
}

2. Виджеты макета (Layout)

Container — универсальный контейнер с отступами, размерами, цветом:

Container(
  width: 200,
  height: 100,
  padding: EdgeInsets.all(16),
  margin: EdgeInsets.all(8),
  color: Colors.blue,
  child: Text('Hello'),
)

Row/Column — располагают дочерние виджеты горизонтально/вертикально:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [Text('A'), Text('B'), Text('C')],
)

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [Text('Line 1'), Text('Line 2')],
)

Stack — наслаивает виджеты друг на друга:

Stack(
  children: [
    Container(color: Colors.blue),
    Positioned(
      top: 20,
      left: 20,
      child: Text('Overlay'),
    ),
  ],
)

ListView — скроллируемый список:

ListView(
  children: [
    ListTile(title: Text('Item 1')),
    ListTile(title: Text('Item 2')),
  ],
)

// Более эффективно:
ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) => ListTile(
    title: Text(items[index]),
  ),
)

GridView — сетка элементов:

GridView.count(
  crossAxisCount: 2,
  children: List.generate(
    20,
    (index) => Container(color: Colors.blue),
  ),
)

Wrap — переносит элементы на следующую строку:

Wrap(
  spacing: 8,
  children: List.generate(
    10,
    (i) => Chip(label: Text('Tag $i')),
  ),
)

3. Input виджеты

TextField — для ввода текста:

TextField(
  decoration: InputDecoration(
    hintText: 'Enter your name',
    border: OutlineInputBorder(),
  ),
  onChanged: (value) => print(value),
)

Checkbox/Radio — для выбора:

Checkbox(
  value: isChecked,
  onChanged: (newValue) => setState(() => isChecked = newValue),
)

Radio(
  value: 'option1',
  groupValue: selectedOption,
  onChanged: (newValue) => setState(() => selectedOption = newValue),
)

DropdownButton — выпадающий список:

DropdownButton<String>(
  value: selectedValue,
  items: ['Option 1', 'Option 2'].map(
    (value) => DropdownMenuItem(value: value, child: Text(value)),
  ).toList(),
  onChanged: (value) => setState(() => selectedValue = value),
)

Slider — для выбора значения:

Slider(
  min: 0,
  max: 100,
  value: sliderValue,
  onChanged: (newValue) => setState(() => sliderValue = newValue),
)

4. Display виджеты

Text — текст:

Text(
  'Hello World',
  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
)

Image — изображения:

Image.network('https://example.com/image.jpg')
Image.asset('assets/images/logo.png')

Icon — иконки Material Design:

Icon(Icons.favorite, color: Colors.red)

Card — красивая карточка с тенью:

Card(
  elevation: 8,
  child: Padding(
    padding: EdgeInsets.all(16),
    child: Text('Card content'),
  ),
)

5. Button виджеты

ElevatedButton — кнопка с тенью:

ElevatedButton(
  onPressed: () {},
  child: Text('Click me'),
)

TextButton — простая кнопка (текст):

TextButton(onPressed: () {}, child: Text('Link'))

IconButton — кнопка с иконкой:

IconButton(icon: Icon(Icons.menu), onPressed: () {})

6. Navigation виджеты

Scaffold — основная структура страницы:

Scaffold(
  appBar: AppBar(title: Text('Title')),
  body: Center(child: Text('Content')),
  floatingActionButton: FloatingActionButton(
    onPressed: () {},
    child: Icon(Icons.add),
  ),
  bottomNavigationBar: BottomNavigationBar(
    items: [...],
  ),
)

TabBar/TabBarView — вкладки:

DefaultTabController(
  length: 3,
  child: Scaffold(
    appBar: AppBar(
      bottom: TabBar(tabs: [Tab(text: 'Tab1'), Tab(text: 'Tab2')]),
    ),
    body: TabBarView(
      children: [Page1(), Page2()],
    ),
  ),
)

7. Специализированные виджеты

AnimatedBuilder — для анимаций:

AnimatedBuilder(
  animation: controller,
  builder: (context, child) => Transform.rotate(
    angle: controller.value * 2 * pi,
    child: Container(color: Colors.blue),
  ),
)

GestureDetector — для обработки жестов:

GestureDetector(
  onTap: () => print('Tapped'),
  onLongPress: () => print('Long pressed'),
  onPanUpdate: (details) => print('Dragged'),
  child: Container(color: Colors.blue),
)

SingleChildScrollView — для прокрутки одного виджета:

SingleChildScrollView(
  child: Column(children: [...]),
)

Часто используемые комбинации

ЗадачаВиджеты
Список товаровListView.builder + Card
ФормаColumn + TextField + ElevatedButton
Главная страницаScaffold + AppBar + FloatingActionButton
ВкладкиDefaultTabController + TabBar
Сетка фотоGridView.builder + Image

Знание базовых виджетов — фундамент Flutter разработки. Используйте composition (комбинирование) вместо создания custom виджетов.

Какие знаешь виды виджетов? | PrepBro