Enum을 문자열로 변환하는 과정을 복잡한 EnumName.ValueName 구문 없이 간단하게 만들어주는 Dart 패키지입니다. enum 값의 문자열 표현을 얻는 데 깔끔하고 직관적인 방법을 제공하여 가독성을 높이고 반복 코드를 줄입니다. 자주 enum을 다루는 개발자들이 더 간단한 toString() 대안을 원할 때 이상적입니다. 이 패키지는 모든 주요 플랫폼을 지원하며 Flutter 프로젝트에 쉽게 통합됩니다.
사용 사례
UI에서 열거형 값을 읽기 쉬운 문자열로 변환하는 방법
열거형 데이터 직렬화 간소화
로그에서 열거형 상태를 기록할 때 코드 가독성 향상
API 요청 또는 구성에서 열거 문자열 사용
반복적인 EnumName.ValueName 참조 피하기
주요 기능
정제된 열거형에서 문자열로의 변환
지나친 열거형 구문을 제거합니다
모든 플러터 플랫폼을 지원합니다
최소한의 설정 및 통합
코드 유지보수성을 향상시킵니다
적합한 대상
enum을 사용하는 Flutter 개발자
열거형 문자열 직렬화가 필요한 프로젝트
클린하고 가독성 높은 코드를 우선시하는 팀
자주 열거형을 사용하는 애플리케이션
반복 코드를 줄이려는 개발자
고려 사항
열거형 수동 등록 필요
모든 고급 열거형 패턴을 지원하지 않을 수 있습니다
기본 문자열 표현 요구 사항에 제한됨
복잡한 열거형 변환에 적합하지 않습니다
정확한 열거형 구현에 의존함
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
enum_to_string
Better conversion of ENUMs to string - It also can handle converting back again!
What it does
It takes an enum such as:
enum TestEnum { testValue1 }
and converts it to
testValue1
Also handles camel case
Input enum TestEnum { testValue1 }
Output Test value 1
You can also capitalize all words using the capitalizeWords flag:
Input enum TestEnum { testValue1 }
Output with capitalizeWords: true: Test Value 1
Usage
import'package:enum_to_string/enum_to_string.dart';
enumTestEnum { testValue1, testValue2 };
convert(){
String result = EnumToString.convertToString(TestEnum.testValue1);
//result = 'testValue1'String result = EnumToString.convertToString(TestEnum.testValue1, camelCase: true);
//result = 'Test value 1'String result = EnumToString.convertToString(TestEnum.testValue1, camelCase: true, capitalizeWords: true);
//result = 'Test Value 1'EnumToString.fromString(TestEnum.values, "testValue1"); //Enum// TestEnum.testValue1EnumToString.fromString(TestEnum.values, "Test Value 1", camelCase: true);
// TestEnum.testValue1List<String> result = EnumToString.toList(TestEnum.values);
//result = ['testValue1','testValue2'],List<String> result = EnumToString.toList(TestEnum.values, camelCase: true);
//result = ['Test value 1','Test value 2'],List result = EnumToString.fromList(TestEnum.values, ["ValueOne", "Value2"]); //List<Enum>//result = [TestEnum.valueOne, TestEnum.value2];
}
Contributing
Any pull requests / extensions welcome, this was just an annoying thing I needed to fix a couple of times so viola! a package was born.
The project uses GitHub Actions for CI (migrated from Travis CI), which automatically runs the following checks on all pull requests:
Dart formatting
Static analysis
Tests
You can run all checks locally before submitting a PR using the provided script:
./tool/check.sh
Or run them individually:
# Get dependencies
dart pub get
# Format code
dart format --output=none --set-exit-if-changed .
# Run static analysis
dart analyze
# Run tests
dart test
The CI pipeline requires all tests to pass. Please ensure your changes include appropriate test coverage.
Enhanced Enum Support (Dart 2.17+)
Starting from version 2.2.0, this package supports Dart's enhanced enums with custom string mappings. This is particularly useful when you need enum string representations that can't be valid Dart identifiers.
enumRating {
G,
PG13('PG-13'), // Custom mapping with hyphen
R,
unrated; // Falls back to normal EnumToString behaviorfinalString? value;
constRating([this.value]);
}
voidmain() {
// Custom mapped values use their explicit mappingprint(EnumToString.convertToString(Rating.PG13)); // Prints: PG-13// Unmapped values use normal EnumToString behaviorprint(EnumToString.convertToString(Rating.unrated)); // Prints: unrated// All other EnumToString features work as expectedprint(EnumToString.fromString(Rating.values, 'PG-13') == Rating.PG13); // trueprint(EnumToString.toList(Rating.values)); // ['G', 'PG-13', 'R', 'unrated']
}
This feature is particularly useful when:
- You need special characters in your enum strings (like hyphens or spaces)
- Yourenum strings need to match an external API or format exactly
- You want some enum values to have custom string representations while others use the default behavior