https://dart.dev/language/extension-types
Dart의 Primitive 타입들은 모두 오브젝트다.
또한 모든 타입 오브젝트들은 다양한 API들을 지원한다.
extension은 이런 API에 커스텀 메소드를 추가할 수 있는 기능이다.
Flutter로 UI 코드를 작성하면서 가장 많이 쓰게되는 위젯 중 하나는 TextStyle이다.
TextStyle을 예시로 Extension 사용법을 정리해본다.
반복되는 TextStyle 코드를 제거하기 위해 텍스트 스타일을 변수로 선언하여 할당해주는 방법을 사용할 수 있을 것이다.
final myTextStyle = TextStyle(color : Colors.amber);
이와 다르게 Extension으로 TextStyle을 미리 만들어 사용할 수 있는 방법도 있다.
extension CustomTextStyle on TextStyle {
TextStyle get heading1 => copyWith(
fontFamily: fontFamily,
fontSize: 28,
color: basicTextColor,
height: 1.3,
);
}
이렇게 작성한 TextStyle Extension은 다음처럼 활용이 가능하다.
Text(
'text',
style: TextStyle().heading1,
),
만약 color값을 바꿔주고 싶다면 TextStyle안에 color를 다시 작성해줘도 되고, copyWith을 사용하여 변경해줄 수 있다.
Text(
'text',
style: TextStyle().heading1.copyWith(color:Colors.amber),
),
DateTime, int, String 과 같이 Dart에서 지원하는 타입들에 필요한 메소드 API를 추가할 수 있다는 것은 매우 매력적인 작업이라고 생각된다.
이뿐만 아니라 enum과 같은 클래스에도 사용할 수 있으니 적극적으로 활용하여 반복되는 코드를 줄여보면 좋을 것 같다.