[flutter] 위젯 속성값 변경 도와주는 copyWith()
플러터 위젯 속성값 변경을 도와주는 copyWith()
위젯을 커스텀하다 보면 변경하고 싶은 속성값은 1개뿐인데, 모든 속성값을 입력하지 않았다며... 필수 속성값을 입력하라는 오류를 경험해보신 적 있을 거예요. 특히 themeData와 같이 필수 속성값이 여러 개인 위젯을 사용할 때 많이 번거로웠습니다.
이러한 불편은 copyWith() 함수를 사용하면 해결할 수 있습니다. 위젯의 기존 속성값은 그대로 사용하면서 변경하려는 속성값의 코드만 작성하면 되도록 도와주거든요.
샘플 코드
class TitleColorThemeCopy extends StatelessWidget {
  const TitleColorThemeCopy({Key? key, required this.child, required this.titleColor}) : super(key: key);
  final Color titleColor;
  final Widget child;
  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return Theme(
      data: theme.copyWith(
        textTheme: theme.textTheme.copyWith(
          titleLarge: theme.textTheme.titleLarge!.copyWith(  // copyWith
            color: titleColor,
          ), 
        ),
      ),
      child: child,
    );
  }
}
코드와 관련해서 궁금하게 있으시다면 댓글 남겨주세요~😊
반응형
    
    
    
  '주제 > flutter' 카테고리의 다른 글
| [flutter] 리스트 스크롤 적용하기 (0) | 2022.04.10 | 
|---|---|
| [flutter] ListView builder, separated widget (0) | 2022.04.10 | 
| [flutter] cached_network_image package (0) | 2022.04.09 | 
| [flutter] 앱 테마 설정하기 (0) | 2022.04.03 | 
| [flutter] Class.fromMap (0) | 2022.03.20 |