Flutter Custom widget styling


Flutter에서 사용자 정의 위젯(Custom Widget)은 반복적으로 사용하는 UI 요소를 캡슐화하고 재사용 가능한 형태로 만들 때 유용합니다. Custom Widget에 스타일을 적용하는 것은 기본 위젯에 스타일을 적용하는 것과 유사하지만, 사용자 정의 위젯에 맞게 스타일 속성을 노출하고 관리하는 방법이 추가됩니다. 이를 통해 유지보수성과 코드의 가독성을 높일 수 있습니다.

Custom Widget 생성 및 스타일링

1. 기본 Custom Widget

먼저 간단한 사용자 정의 버튼 위젯을 만들어 보겠습니다.

import 'package:flutter/material.dart';

class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  CustomButton({required this.text, required this.onPressed});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(text),
    );
  }
}

위의 예시는 텍스트와 콜백 함수를 매개변수로 받아 ElevatedButton을 생성하는 간단한 사용자 정의 위젯입니다.

2. 스타일 속성 추가

이제 이 Custom Widget에 스타일 속성을 추가하여 사용자가 스타일을 설정할 수 있도록 하겠습니다.

import 'package:flutter/material.dart';

class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color? color;
  final TextStyle? textStyle;
  final double? padding;

  CustomButton({
    required this.text,
    required this.onPressed,
    this.color,
    this.textStyle,
    this.padding,
  });

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        primary: color ?? Theme.of(context).primaryColor,
        padding: EdgeInsets.all(padding ?? 16.0),
      ),
      onPressed: onPressed,
      child: Text(
        text,
        style: textStyle ?? TextStyle(fontSize: 16),
      ),
    );
  }
}

여기서 우리는 color, textStyle, padding과 같은 선택적 스타일 속성을 추가했습니다. 사용자가 이 속성을 통해 버튼의 색상, 텍스트 스타일, 패딩을 설정할 수 있습니다.

3. Custom Widget 사용

이제 이 사용자 정의 위젯을 사용하여 스타일을 적용할 수 있습니다.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Custom Widget Styling Example')),
        body: Center(
          child: CustomButton(
            text: 'Click Me',
            onPressed: () {
              print('Button Pressed');
            },
            color: Colors.red,
            textStyle: TextStyle(color: Colors.white, fontSize: 20),
            padding: 20.0,
          ),
        ),
      ),
    );
  }
}

이 예시는 CustomButton을 사용하여 버튼의 색상, 텍스트 스타일, 패딩을 설정한 것입니다.

결론

Flutter에서 Custom Widget을 생성하고 스타일링하는 것은 애플리케이션의 일관된 UI를 유지하고 코드의 재사용성을 높이는 데 매우 유용합니다. 기본 위젯에 스타일 속성을 추가하여 Custom Widget을 확장하고, 이를 통해 더 많은 컨트롤과 유연성을 제공할 수 있습니다. Custom Widget을 효과적으로 사용하면 유지보수가 쉬워지고, UI 코드의 가독성이 크게 향상됩니다.


Leave a Reply

Your email address will not be published. Required fields are marked *