create-catalog-item

Use esta habilidade quando o usuário solicitar a criação de um novo CatalogItem, classe de dados e/ou classe de widget com base em uma definição de JSON Schema em um aplicativo que utiliza…

npx skills add https://github.com/flutter/genui --skill create-catalog-item

Create CatalogItem

Goal

To correctly implement a GenUI CatalogItem based on a provided json_schema_builder Schema, including its corresponding data class, CatalogItem instance, and Widget class. This ensures the AI model can properly generate and interact with the UI component.

Instructions

When tasked with creating a CatalogItem from a Schema, follow these steps:

  1. Create the Data Class:

    • Name it _<SchemaName>Data (e.g., if schema is myCardSchema, data class is _MyCardData).
    • Add final fields for each property defined in the schema.
    • Create a factory _<SchemaName>Data.fromJson(Map<String, Object?> json) method.
    • Use a try-catch block to parse the properties and return a new instance.
    • Cast each property from the json map to its expected type, e.g., title: json['title'] as String, or action: json['action'] as JsonMap?,.
    • Throw an Exception('Invalid JSON for _<SchemaName>Data') in the catch block if an error occurs.
  2. Create the CatalogItem Instance:

    • Name it identical to the schema name but without the "Schema" suffix (e.g., myCard for myCardSchema).
    • Declare as a final CatalogItem.
    • Set name to the capitalized version of the name (e.g., 'MyCard').
    • Set dataSchema to the provided schema.
    • Implement the widgetBuilder: (itemContext):
      • Cast itemContext.data to Map<String, Object?>.
      • Parse the data using the data class fromJson method: _<SchemaName>Data.fromJson(json).
      • Return the corresponding Widget class and pass the required data.
      • If the schema includes an action callback (like onCompleted), implement it here. You must parse the action context using resolveContext and dispatch an event using itemContext.dispatchEvent(...).
  3. Create the Widget Class:

    • Name it _<CapitalizedSchemaName> (e.g., _MyCard).
    • Inherit from StatelessWidget or StatefulWidget depending on state requirements.
    • Add the Data Class as a required property (e.g., final _<SchemaName>Data data;).
    • Add any required callback properties (e.g., final void Function(int) onCompleted;).
    • Implement the build method using Flutter Material components (e.g., Card, Column, Text). Make sure each data field in the data class is displayed, and that actions are represented by buttons or other interactive elements.

Examples

Input Schema

final basicCardSchema = S.object(
  properties: {
    'component': S.string(enumValues: ['BasicCard']),
    'title': S.string(),
    'description': 
    'action': A2uiSchemas.action(),
  },
  required: ['title'],
);

Expected Output

class _BasicCardData {
  final String title;
  final JsonMap? action;

  _BasicCardData({required this.title, this.action});

  factory _BasicCardData.fromJson(Map<String, Object?> json) {
    try {
      return _BasicCardData(
        title: json['title'] as String,
        action: json['action'] as JsonMap?,
      );
    } catch (e) {
      throw Exception('Invalid JSON for _BasicCardData: $e');
    }
  }
}

final basicCard = CatalogItem(
  name: 'BasicCard',
  dataSchema: basicCardSchema,
  widgetBuilder: (itemContext) {
    final json = itemContext.data as Map<String, Object?>;
    final data = _BasicCardData.fromJson(json);

    return _BasicCard(
      data: data,
      onTap: () async {
        final action = data.action;
        if (action == null) return;
        final event = action['event'] as JsonMap?;
        final name = (event?['name'] as String?) ?? '';
        final JsonMap contextDefinition =
            (event?['context'] as JsonMap?) ?? <String, Object?>{};
        final JsonMap resolvedContext = await resolveContext(
          itemContext.dataContext,
          contextDefinition,
        );
        itemContext.dispatchEvent(
          UserActionEvent(
            name: name,
            sourceComponentId: itemContext.id,
            context: resolvedContext,
          ),
        );
      }
    );
  },
);

class _BasicCard extends StatelessWidget {
  final _BasicCardData data;
  final VoidCallback onTap;

  const _BasicCard({super.key, required this.data, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ListTile(
        title: Text(data.title),
        onTap: onTap,
      ),
    );
  }
}

Constraints

  • Ensure proper use of try-catch blocks and type casting when parsing JSON in fromJson.
  • Make sure action resolution accurately fetches variables via resolveContext and uses itemContext.dispatchEvent when actions are present in the Schema.

Mais skills de flutter

dart-modern-features
flutter
Para encontrar candidatos para modernização:
flutter-fix-layout-issues
flutter
Corrige erros de layout do Flutter (overflow, restrições ilimitadas) usando ferramentas Dart e Flutter MCP. Use ao lidar com "RenderFlex overflowed", "Vertical…
adding-release-notes
flutter
Adiciona descrições de mudanças voltadas ao usuário nas notas de versão do DevTools. Use ao documentar melhorias, correções ou novos recursos no arquivo NEXT_RELEASE_NOTES.md.
reviewing-devtools-prs
flutter
Fluxo de revisão de PR específico do repositório DevTools, aplicando as diretrizes de estilo do DevTools e padrões comuns de revisão. Use ao revisar pull requests no…
dart-use-primary-constructors
flutter
Ajude os usuários a escrever construtores primários sintática e semanticamente corretos em Dart, e a migrar/usar a nova sintaxe de construtores, a sintaxe de corpo vazio com ponto e vírgula,…
code-documentation
flutter
Guia para escrever documentação de código eficaz, incluindo docstrings, JSDoc, dartdoc e comentários de implementação. Use esta skill ao escrever novo código, adicionar…
api-review
flutter
Revisa o código especificado em relação às diretrizes canônicas de Design de API. Use esta skill quando o usuário pedir uma revisão de API ou para verificar o código em relação ao design de API…
flutter-accessibility
flutter
Implementa os padrões de acessibilidade WCAG 2 e EN 301 549 e layouts adaptativos em aplicativos Flutter. Aplica anotações semânticas, tamanhos mínimos de alvo de toque (48x48 dp) e taxas de contraste de texto (4,5:1 para texto pequeno, 3:1 para texto grande) nas plataformas mobile, web e desktop. Inclui lógica de decisão para inicialização de semântica web, encapsulamento de widgets interativos, alternância de layout baseada no tamanho da tela e tratamento de entrada por teclado/mouse. Gerencia o percurso de foco via FocusTraversalGroup e...