К основному содержанию
скилл CX Codex

flutter-fix-layout-issues — скилл для Claude Code: чинит ошибки

Разбирает ошибки раскладки Flutter по тексту исключения: overflow, неограниченные constraints, неверный ParentData. Подсказывает, что обернуть и во что.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add flutter/agent-plugins --skill flutter-fix-layout-issues -a claude-code
Открыть на GitHub

Что делает flutter-fix-layout-issues

Скилл опирается на простое правило Flutter: размеры идут снизу вверх, ограничения сверху вниз. Когда эти договорённости нарушаются, в консоли появляется конкретная сигнатура ошибки, и по ней уже понятно, где искать. «Vertical viewport was given unbounded height» — прокручиваемый виджет поставили в Column. «An InputDecorator...cannot have an unbounded width» — TextField оказался в Row без ограничения по ширине. «RenderFlex overflowed» — ребёнок Row или Column просит больше, чем ему выделили; на экране это жёлто-чёрные полосы.

Дальше идёт чек-лист: запустить приложение в debug-режиме, поймать первое исключение в консоли и не отвлекаться на каскадные «RenderBox was not laid out» — их нужно пропускать и смотреть выше по стеку. Для каждого типа ошибки свой рецепт: обернуть список в Expanded или SizedBox, текстовое поле — в Expanded либо Flexible, переполненного ребёнка — в Expanded (вписать) или Flexible (разрешить быть меньше). После правки — hot reload и проверка, что красный экран или полосы ушли.

Отдельный случай — «Incorrect use of ParentData widget»: ParentDataWidget должен быть прямым потомком своего родителя. Expanded и Flexible живут только внутри Row, Column или Flex, Positioned — только внутри Stack. Скилл заявлен для Dart и Flutter MCP-инструментов, так что без подключённого MCP-сервера рассчитывать придётся только на текст ошибки и код перед глазами.

Какие задачи решает

  • Убрать жёлто-чёрные полосы переполнения в Row или Column
  • Починить «Vertical viewport was given unbounded height» у ListView внутри Column
  • Задать ширину TextField, который ругается на неограниченную ширину
  • Найти настоящую причину ошибки среди каскадных «RenderBox was not laid out»
  • Переставить Expanded или Positioned прямым потомком нужного родителя

Примеры запросов агенту

  • В консоли «RenderFlex overflowed» — найди переполненный виджет и оберни его в Expanded
  • Поправь вёрстку: ListView внутри Column даёт unbounded height, нужен Expanded
  • Разбери стек ошибки и объясни, почему Positioned ругается на ParentData

Как установить flutter-fix-layout-issues

1Через Skills CLI (Vercel)

npx skills add flutter/agent-plugins --skill flutter-fix-layout-issues -a claude-code

2Вручную: положить файлы

~/.claude/skills/flutter-fix-layout-issues/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/flutter-fix-layout-issues/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о flutter-fix-layout-issues

Как установить flutter-fix-layout-issues в Claude Code?

Выполните npx skills add flutter/agent-plugins --skill flutter-fix-layout-issues -a claude-code. Скилл появится по пути ~/.claude/skills/flutter-fix-layout-issues/SKILL.md.

Что делает flutter-fix-layout-issues?

Сопоставляет текст ошибки раскладки Flutter с типом нарушения ограничений и предлагает конкретную обёртку: Expanded, Flexible или SizedBox.

Какие ошибки он разбирает?

«Vertical viewport was given unbounded height», «An InputDecorator...cannot have an unbounded width», «RenderFlex overflowed» и «Incorrect use of ParentData widget».

Исходный текст

SKILL.md · BSD-3-Clause
---
name: flutter-fix-layout-issues
description: Fixes Flutter layout errors (overflows, unbounded constraints) using Dart and Flutter MCP tools. Use when addressing "RenderFlex overflowed", "Vertical viewport was given unbounded height", or similar layout issues.
metadata:
  model: models/gemini-3.1-pro-preview
  last_modified: Tue, 21 Apr 2026 19:45:59 GMT
---
# Resolving Flutter Layout Errors

## Contents
- [Constraint Violation Diagnostics](#constraint-violation-diagnostics)
- [Layout Error Resolution Workflow](#layout-error-resolution-workflow)
- [Examples](#examples)

## Constraint Violation Diagnostics

Flutter layout operates on a strict rule: **Constraints go down. Sizes go up. Parent sets position.** Layout errors occur when this negotiation fails, typically due to unbounded constraints or unconstrained children. 

Diagnose layout failures using the following error signatures:

*   **"Vertical viewport was given unbounded height"**: Triggered when a scrollable widget (`ListView`, `GridView`) is placed inside an unconstrained vertical parent (`Column`). The parent provides infinite height, and the child attempts to expand infinitely.
*   **"An InputDecorator...cannot have an unbounded width"**: Triggered when a `TextField` or `TextFormField` is placed inside an unconstrained horizontal parent (`Row`). The text field attempts to determine its width based on infinite available space.
*   **"RenderFlex overflowed"**: Triggered when a child of a `Row` or `Column` requests a size larger than the parent's allocated constraints. Visually indicated by yellow and black warning stripes.
*   **"Incorrect use of ParentData widget"**: Triggered when a `ParentDataWidget` is not a direct descendant of its required ancestor. (e.g., `Expanded` outside a `Flex`, `Positioned` outside a `Stack`).
*   **"RenderBox was not laid out"**: A cascading side-effect error. Ignore this and look further up the stack trace for the primary constraint violation (usually an unbounded height/width error).

## Layout Error Resolution Workflow

Copy and use this checklist to systematically resolve layout constraint violations.

### Task Progress
- [ ] Run the application in debug mode to capture the exact layout exception in the console.
- [ ] Identify the primary error message (ignore cascading "RenderBox was not laid out" errors).
- [ ] Apply the conditional fix based on the specific error type:
  - **If "Vertical viewport was given unbounded height"**: Wrap the scrollable child (`ListView`, `GridView`) in an `Expanded` widget to consume remaining space, or wrap it in a `SizedBox` to provide an absolute height constraint.
  - **If "An InputDecorator...cannot have an unbounded width"**: Wrap the `TextField` or `TextFormField` in an `Expanded` or `Flexible` widget.
  - **If "RenderFlex overflowed"**: Constrain the overflowing child by wrapping it in an `Expanded` widget (to force it to fit) or a `Flexible` widget (to allow it to be smaller than the allocated space).
  - **If "Incorrect use of ParentData widget"**: Move the `ParentDataWidget` to be a direct child of its required parent. Ensure `Expanded`/`Flexible` are direct children of `Row`/`Column`/`Flex`. Ensure `Positioned` is a direct child of `Stack`.
- [ ] Execute Flutter hot reload.
- [ ] Run validator -> review errors -> fix: Inspect the UI to verify the red/grey error screen or yellow/black overflow stripes are resolved. If new layout errors appear, repeat the workflow.

## Examples

### Fixing Unbounded Height (ListView in Column)

**Input (Error State):**
```dart
// Throws "Vertical viewport was given unbounded height"
Column(
  children: <Widget>[
    const Text('Header'),
    ListView(
      children: const <Widget>[
        ListTile(title: Text('Item 1')),
        ListTile(title: Text('Item 2')),
      ],
    ),
  ],
)
```

**Output (Resolved State):**
```dart
// Wrap ListView in Expanded to constrain its height to the remaining Column space
Column(
  children: <Widget>[
    const Text('Header'),
    Expanded(
      child: ListView(
        children: const <Widget>[
          ListTile(title: Text('Item 1')),
          ListTile(title: Text('Item 2')),
        ],
      ),
    ),
  ],
)
```

### Fixing Unbounded Width (TextField in Row)

**Input (Error State):**
```dart
// Throws "An InputDecorator...cannot have an unbounded width"
Row(
  children: [
    const Icon(Icons.search),
    TextField(), 
  ],
)
```

**Output (Resolved State):**
```dart
// Wrap TextField in Expanded to constrain its width to the remaining Row space
Row(
  children: [
    const Icon(Icons.search),
    Expanded(
      child: TextField(),
    ),
  ],
)
```

### Fixing RenderFlex Overflow

**Input (Error State):**
```dart
// Throws "A RenderFlex overflowed by X pixels on the right"
Row(
  children: [
    const Icon(Icons.info),
    const Text('This is a very long text string that will definitely overflow the available screen width and cause a RenderFlex error.'),
  ],
)
```

**Output (Resolved State):**
```dart
// Wrap the Text widget in Expanded to force it to wrap within the available constraints
Row(
  children: [
    const Icon(Icons.info),
    Expanded(
      child: const Text('This is a very long text string that will definitely overflow the available screen width and cause a RenderFlex error.'),
    ),
  ],
)
```

© flutter · BSD-3-Clause · flutter/agent-plugins

Похожие скиллы

Всё по теме «Мобильная разработка» →
vercel-react-native-skills vercel Набор правил по React Native и Expo для ИИ-агента: списки, анимации, навигация. Пригодится, когда агент правит мобильный код и надо, чтобы он делал это одинаково. CX Codex +1 255 200установок animate-expo emilkowalski Создаёт мобильные анимации для React Native и Expo на базе Reanimated и Gesture Handler. Помогает избежать просадок кадров на реальных устройствах. CX Codex +1 137 900установок mobile-native emilkowalski Убирает мелочи, из-за которых веб-приложение на телефоне выдаёт себя: залипающий hover, вспышку при тапе, ошибку с 100vh. CX Codex +1 86 600установок aso coreyhaines31 Анализирует страницы приложений в App Store и Google Play по правилам поисковой оптимизации. Находит слабые места в метаданных, графике и конверсии. CX Codex +1 75 400установок swiftui-pro Paul Hudson Проверяет SwiftUI-код на устаревшие API, ошибки в структуре и проблемы доступности. Пригодится для ревью и доработки проектов на SwiftUI. CX Codex +1 35 200установок orca-emulator stablyai Управляет iOS Simulator внутри Orca с живым экраном устройства. Пригодится для тапов, жестов, поворота экрана и сбора доказательств работы iOS-приложения. CX Codex +1 5 800установок

Из того же набора15

Весь набор →
flutter-apply-architecture-best-practices Скилл раскладывает Flutter-приложение по слоям UI, Logic и Data. Пригодится для нового проекта или рефакторинга кода. CX Codex +1 43 200установок flutter-build-responsive-layout Скилл обучает агента строить адаптивные интерфейсы Flutter под экраны телефонов и десктопов. Он задаёт правила работы с LayoutBuilder и MediaQuery. CX Codex +1 42 500установок flutter-add-widget-test Скилл помогает писать компонентные тесты Flutter с помощью WidgetTester. Проверяет, как виджет отображается и реагирует на касания, скролл и ввод текста. CX Codex +1 39 200установок flutter-add-integration-test Скилл настраивает интеграционные тесты во Flutter через пакет integration_test. Он переносит действия из MCP-сервера в готовые тестовые сценарии. CX Codex +1 38 200установок flutter-setup-declarative-routing Настраивает декларативную маршрутизацию Flutter через go_router: маршруты по URL, вложенную навигацию и глубокие ссылки для веба и мобильных платформ. CX Codex +1 37 800установок flutter-implement-json-serialization Скилл учит агента создавать Dart-модели с методами fromJson и toJson через библиотеку dart:convert. Пригодится при ручном разборе простых структур данных в Flutter. CX Codex +1 37 400установок flutter-add-widget-preview Скилл учит агента создавать интерактивные превью виджетов во Flutter через package:flutter/widget_previews.dart. Пригодится для изолированной вёрстки UI без сборки всего приложения. CX Codex +1 36 800установок flutter-setup-localization Скилл автоматизирует инициализацию поддержки многоязычности в Flutter-проекте. Добавляет зависимости, включает генерацию кода и создаёт конфиг для работы с .arb-файлами. CX Codex +1 36 800установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой