-
[Package] WidgetBook 파라미터 적용(Knobs)플러터/Packages 2024. 3. 17. 11:57
Knobs?
"Knobs(노브)"은 Widgetbook에서 동적 도구로, 실행 중에 유스케이스에 전달되는 매개변수를 수정할 수 있게 해줍니다. 이를 통해 여러 조건과 입력 하에서 위젯을 조정하고 검토하여, 구성 요소의 동작을 개선하고 이해하는 데 도움이 됩니다.
실시간으로 파라미터를 변경하여 위젯을 확인할 수 있다.
아래와 같은 파라미터를 사용할 수 있다.
Knobs 적용
1. 테스트를 위한 TestIconImage라는 위젯 작성
- 아이콘과 텍스트를 같이 출력하는 위젯
- size, iconData, color, text, textShow 파라미터 사용
import 'package:flutter/material.dart'; enum ImageSize { BIG, SMALL } class TestIconImage extends StatelessWidget { final ImageSize size; final IconData iconData; final Color color; final String text; final bool textShow; const TestIconImage({super.key, required this.iconData, required this.color, required this.text, required this.size, this.textShow = true}); @override Widget build(BuildContext context) { return Column(children: [ Icon(iconData, size: size == ImageSize.BIG ? 40 : 20, color: color), Visibility( visible: textShow, child: Text(text, style: const TextStyle(color: Colors.black),)) ],); } }
2. usecase 코드 작성
import 'test_icon_image.dart'; import 'package:flutter/material.dart'; import 'package:widgetbook_annotation/widgetbook_annotation.dart' as widgetbook; @widgetbook.UseCase( name: 'TestIconImage', type: TestIconImage, ) Widget testIconImageUseCase(BuildContext context) { return Center( child: TestIconImage( iconData: Icons.access_time_sharp, color: Colors.black, text: "text", size: ImageSize.SMALL), ); }
3. usecase에 knobs 추가
- size, color는 combobox로 선택 가능
- text는 string값을 입력 받게
- textShow는 bool값을 선택할 수 있게 수정
@widgetbook.UseCase( name: 'TestIconImage', type: TestIconImage, ) Widget testIconImageUseCase(BuildContext context) { String size = context.knobs .list<String>(label: "image size", options: ["BIG", "SMALL"]); Color color = context.knobs.list<Color>( label: "image color", options: [const Color(0xff00ff00), const Color(0xffff0000), Colors.black], initialOption: Colors.red); return Center( child: TestIconImage( iconData: Icons.access_time_sharp, color: color, text: context.knobs.string(label: "text", initialValue: "init text"), textShow: context.knobs.boolean(label: "text show"), size: ImageSize.values.where((element) => element.name == size).first), ); }
이렇게 하면 쉽게 위젯 테스트가 가능하다.
'플러터 > Packages' 카테고리의 다른 글
[Riverpod] Riverpod으로 Theme관리 (0) 2024.05.22 [Package] go_router를 사용한 화면 이동 (0) 2024.04.22 [Package] WidgetBook 설치 및 테스트 (0) 2024.03.03