[Flutter] Button Style 지정하기

2023. 6. 21. 13:32·🐦 플러터

기본 스타일 지정

ElevatedButton(
      child: Text('styleFrom'),
      onPressed: (){},

      // Set style using styleFrom
      style: ElevatedButton.styleFrom(
          primary: Colors.blue,
          fixedSize: Size(200,50),
          elevation: 20.0
      )
)

위의 코드처럼 기본적으로 styleFrom()을 이용해서 버튼들의 스타일을 지정해 줄 수 있습니다.

이 방법은 워낙 기본적인 거라 다들 알거라고 생각합니다.

Press 유무에 따라 스타일 지정

ElevatedButton(
        child: Text('ButtonStyle'),
        onPressed: (){},

        // Set style using ButtonStyle
        style: ButtonStyle(

           // Set backgroundColor depending on whether states is MaterialState.pressed
          backgroundColor: MaterialStateProperty.resolveWith((states) {
            return states.contains(MaterialState.pressed)
                ? Colors.green
                : Colors.blue;
          }),

          // Set fixedSize depending on whether states is MaterialState.pressed
          fixedSize: MaterialStateProperty.resolveWith((states) {
            return states.contains(MaterialState.pressed)
                ? Size(300,100)
                : Size(200,50);
          }),

          // Set elevation regardless of states
          elevation: MaterialStateProperty.resolveWith((states) {
            return 20.0;
          }),
        ),

  )

이 방법은 기존에 내가 몰랐던 방법이라 이렇게 기록해놓으려고 합니다.

ButtonStyle 내부에서 MaterialStateProperty를 사용해서 press시, hover시, focus시 등 여러 경우들에 대해서 스타일을 지정할 수가 있습니다. 위의 코드는 내가 press했을 때 스타일을 변경시키는 예시 코드입니다.

전체 예시 코드

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: PracticeButtonStyle(),
    );
  }
}

class PracticeButtonStyle extends StatefulWidget {
  const PracticeButtonStyle({Key? key}) : super(key: key);

  @override
  State<PracticeButtonStyle> createState() => _PracticeButtonStyle();
}

class _PracticeButtonStyle extends State<PracticeButtonStyle> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(
                child: Text('ButtonStyle'),
                onPressed: (){},

                // Set style using ButtonStyle
                style: ButtonStyle(

                   // Set backgroundColor depending on whether states is MaterialState.pressed
                  backgroundColor: MaterialStateProperty.resolveWith((states) {
                    return states.contains(MaterialState.hovered)
                        ? Colors.green
                        : Colors.blue;
                  }),

                  // Set fixedSize depending on whether states is MaterialState.pressed
                  fixedSize: MaterialStateProperty.resolveWith((states) {
                    return states.contains(MaterialState.hovered)
                        ? Size(300,100)
                        : Size(200,50);
                  }),

                  // Set elevation regardless of states
                  elevation: MaterialStateProperty.resolveWith((states) {
                    return 20.0;
                  }),
                ),

              ),
              ElevatedButton(
                  child: Text('styleFrom'),
                  onPressed: (){},

                  // Set style using styleFrom
                  style: ElevatedButton.styleFrom(
                      primary: Colors.blue,
                      fixedSize: Size(200,50),
                      elevation: 20.0
                  )
              )
            ],
          )
      ),
    );
  }
}

첫 번째 버튼을 hover했을 때의 화면 결과물

이처럼 버튼을 스타일링 할 수 있다는 것을 확인할 수 있습니다.

https://docs.flutter.dev/release/breaking-changes/buttons

 

New Buttons and Button Themes

The basic material button classes have been replaced.

docs.flutter.dev

저작자표시 비영리 동일조건 (새창열림)
'🐦 플러터' 카테고리의 다른 글
  • [Flutter] Auto Size Text 패키지 사용해서 글씨 크기 조절하기
  • [Flutter] 라이트모드, 다크모드 테마 적용하기
  • [Flutter] Responsive User Interface를 구현해보자
  • [Flutter] flutter_screenutil 패키지 알아보기
기멘기
기멘기
Handong Global University | Apple Developer Academy @ POSTECH
  • 기멘기
    현기의 비공식문서 🍎
    기멘기
  • 전체
    오늘
    어제

  • 링크

    • Github
    • Instagram

    • 전체 글 (76) N
      • 🍎 iOS (6)
        • 애플 디벨로퍼 아카데미 (6)
      • 🐦 플러터 (32)
      • 🤔 컴공 지식 (10)
        • 알고리즘 (3)
        • 네트워크 (7)
      • 🔥 문해력 상승 (8)
        • 백 준 (8)
        • 프로 그래머 스 (0)
      • 💬 이모저모 (12)
        • CRA 방학 프로젝트 (4)
        • 캡스톤 산학 프로젝트 (5)
        • PARD IT 협업 동아리 (2)
      • 💡 인사이트 (0)
        • 전공 관련 (0)
        • 기타 (0)
      • ✏️ 하루 회고 (TIL) (1) N
      • 🔍 ETC (7)
        • HTML-CSS-JS (4)

  • 인기 글


  • 최근 댓글


  • 최근 글


  • 블로그 메뉴

    • 티스토리 홈
    • 블로그 관리
    • 글 작성하기

  • hELLO· Designed By정상우.v4.10.3
기멘기
[Flutter] Button Style 지정하기
상단으로

티스토리툴바