[Flutter] 재사용 가능한 위젯 만들기

uengmin·2025년 1월 3일

Flutter

목록 보기
12/20
post-thumbnail

Reusable Widget

위젯을 조금만 바꾸어 사용하는 일이 잦다.
예를 들어 텍스트나 숫자만 바꾼 동일한 디자인의 텍스트박스, 여러 버튼 등이 있다.

단 한번만 사용할 위젯을 만드는 것이 아니라면, 재사용 가능한 위젯을 만드는 것이 훨씬 더 편리하고, 관리하기 용이하다.

Class를 이용한 방법

import 'package:flutter/material.dart';

class Button extends StatelessWidget {
  final String text;
  final Color bgColor;
  final Color textColor;

  const Button({
    super.key,
    required this.text,
    required this.bgColor,
    required this.textColor,
  });

  
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: bgColor, borderRadius: BorderRadius.circular(45)),
      child: Padding(
        padding: const EdgeInsets.symmetric(
          vertical: 20,
          horizontal: 40,
        ),
        child: Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: 20,
          ),
        ),
      ),
    );
  }
}

해당 코드는 아래 코드처럼 사용하면 된다.

Button(
    text: 'Transfer',
    bgColor: Color(0xFFF1B33B),
    textColor: Colors.black),
Button(
    text: 'Request',
    bgColor: Color(0xFF1F2123),
    textColor: Colors.white)

0개의 댓글