본문 바로가기

코딩강의/Flutter 로 웹툰 앱 만들기(플러터-노마드코더)

Reusable Widgets

1. 재사용 가능한 위젯을 만들어보자

 

widgets 폴더 안에 button.dart라는 위젯을 만들었다. (아래 내용 참조)

 

Button 생성자를 만들어 값을 받아오고 적용 시켜 준다. 이 때 원래 Padding 값은 const였으나 새로운 값에 의해 더이상

고정 값(상수 값)이 아니기 때문에 const를 지워주어야 한다.

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});

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

그리고 main.dart 파일에서는 아래와 같이 위에 위젯을 가져다 쓰면 된다. 

                  Button(
                      text: "Request",
                      bgColor: Color(0xFF1F2123),
                      textColor: Colors.white),