create-catalog-item

작성자: flutter

사용자가 JSON Schema 정의를 기반으로 새 CatalogItem, 데이터 클래스 및/또는 위젯 클래스를 생성하도록 요청할 때 이 스킬을 사용하세요.

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.

flutter의 다른 스킬

adding-release-notes
flutter
사용자 대상 변경 사항 설명을 DevTools 릴리스 노트에 추가합니다. NEXT_RELEASE_NOTES.md 파일에 개선 사항, 수정 사항 또는 새로운 기능을 문서화할 때 사용하세요.
official
dart-modern-features
flutter
현대화를 위한 후보를 찾으려면:
official
api-review
flutter
지정된 코드를 표준 API 설계 지침에 맞춰 검토합니다. 사용자가 API 리뷰를 요청하거나 API 설계에 따라 코드를 확인할 때 이 스킬을 사용하세요…
official
code-documentation
flutter
효과적인 코드 문서 작성 가이드로, docstrings, JSDoc, dartdoc 및 구현 주석을 포함합니다. 새 코드를 작성하거나 추가할 때 이 스킬을 사용하세요…
official
dart-add-unit-test
flutter
Write and organize unit tests for functions, methods, and classes using `package:test`. Use when creating new logic or fixing bugs to ensure code remains…
official
dart-build-cli-app
flutter
진입점 구조, 종료 코드, 크로스 플랫폼 스크립트. 명령줄 유틸리티, 스크립트 또는 애플리케이션을 빌드할 때 사용합니다.
official
dart-collect-coverage
flutter
coverage 패키지를 사용하여 커버리지를 수집하고 LCOV 보고서를 생성합니다
official
dart-fix-runtime-errors
flutter
get_runtime_errors와 lsp를 사용하여 활성 스택 트레이스를 가져오고, 실패한 줄을 찾아 수정을 적용한 후 hot_reload를 통해 해결 여부를 확인합니다.
official