[Flutter] Refactor

Tyger·2021년 10월 13일
1

Refactor

flutter 개발을 하다 보면 중복된 widget을 사용하는 경우가 많다

예를들어 같은 종류의 textField나 button 등 이런 위젯이 10개 이상 사용하게 되면 코드가 매우 길어지게 된다

이렇게 중복 코드가 많아지면 flutter 언어 특성상 widget -> widget으로 점점 깊어지는 구조라 코드의 가독성도 떨어지고 이런 코드는 나중에 유지보수 하기가 힘들어 진다

widget을 추출해서 사용하는 방법에 대해 알아보자

vscode
MacOS : cmd + .
Windows : ctrl + .

단축키를 누르면 위젯을 감싸거나 위젯의 위치를 옮기는 기능도 제공된다

실행해 보면 Extract Method, Extract Widget이 있다
method나 widget으로 둘 다 추출 가능하다

button을 만드는 폼을 method로 추출한 것으로 필수 인자값을 통해 custom하는 방식으로 사용이 가능하다

required를 주면 필수 인자 값으로 반드시 받아와야 하는 인자 값이 되고, ?와!는 null에 대한 연산자로 차후에 다룰 예정이다

         _buttonForm(
              width: MediaQuery.of(context).size.width * 0.8,
              reSize: MediaQuery.of(context).size,
              title: 'Test Button2',
              onTap: () {
                showBottomSheet(
                    context: context,
                    backColor: Colors.white,
                    widget: Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(100),
                        color: Colors.red,
                      ),
                    ));
              },
              btnColor: Colors.red,
              borderWidth: 4,
            ),


 Padding _buttonForm({
    required double width,
    required Size reSize,
    required String title,
    required Function() onTap,
    Color? titleColor,
    required Color btnColor,
    double? borderWidth = 1,
  }) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: InkWell(
        onTap: onTap,
        child: Container(
          width: width,
          height: reSize.height * 0.08,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.lightBlue, width: borderWidth!),
              color: btnColor),
          child: Center(
              child: Text(
            title,
            style: theme.textTheme.bodyText2!
                .copyWith(color: titleColor, fontSize: 18),
          )),
        ),
      ),
    );
  }

이렇게 사용하여 인자값으로 widget도 받아오는 형태로 refactoring 할 수 있다

Future showBottomSheet({
    required BuildContext context,
    double? height = 250,
    required Color backColor,
    Widget? widget,
  }) {
    return showModalBottomSheet(
        context: context,
        builder: (context) {
          return Container(
            height: height,
            color: backColor,
            child: widget ??
                const Center(
                  child: Text('test'),
                ),
          );
        });
  }

Example

profile
Flutter Developer

0개의 댓글