Flutter - #11. ElevatedButton

Pearl Lee·2021년 6월 1일
1

Flutter Widget

목록 보기
11/50

내가 보려고 쓰는 Flutter 일기

출처1 : https://api.flutter.dev/flutter/material/ElevatedButton-class.html
출처2 : https://api.flutter.dev/flutter/material/RaisedButton-class.html
출처3 : https://www.youtube.com/watch?v=UUsLgUMvLLI
출처4 : Do it! 플러터 앱 프로그래밍 - 조준수, 이지스퍼블리싱



오늘은 RaisedButton을 배워보려고 하였으나... 찾았더니

딴 거 쓰래
그렇다면 ElevatedButton을 알아보자

RaisedButton 이 원래 사용되던 거라, 유튜브 영상이나 도서에는 RaisedButton을 쓰는 곳이 많았다. 그래서 ElevatedButton에 스타일 적용하는 방법을 찾기가 어려웠는데, 유튜브에서 ElevatedButton의 속성을 자세하게 다뤄주는 사람이 있었다. Erico Darmawan Handoyo

채널 정보에 위치가 인도네시아 라고 되어있어서인지 난생 처음 들어보는 언어였다^^ 그래도 코드는 알아볼 수 있으니까...! 출처3에 해당 영상의 url을 표기해두었다. 나만 보고 싶은 자세한 영상...



ElevatedButton

ElevatedButton 을 누르면 오른쪽과 아래로 그림자가 생겨서, 버튼이 주변 배경보다 높이가 약간 높아지는 느낌이 든다. 버튼 클릭으로 발생하는 이벤트는 onPressed 또는 onLongPress 속성에 추가하면 되고, 이 속성들에 null을 주면 못쓰는 버튼이 된다.(클릭해도 눌러지지 않는다. 그냥 예쁜 네모가 됨)

생긴걸 바꾸려면 style 속성에 ElevatedButton.styleFrom() 을 쓰거나, ButtonStyle()로 조정할 수 있다. 난 ElevatedButton.styleFrom을 사용한 코드로 공부하였다. (ButtonStyle 하다가 헤맸음)




코드 예시로 알아보자

우선 공식 문서에서 제공하는 예제 코드를 먼저 보자. 나는 눈이 잘 안보여서^^ 이번에도 예제 코드에서 크기 조정을 했다.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Demo';

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatefulWidget(),
      ),
    );
  }
}

/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  
  Widget build(BuildContext context) {
    final ButtonStyle style = ElevatedButton.styleFrom(
        textStyle: const TextStyle(fontSize: 40),
        minimumSize: Size(200, 100));

    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ElevatedButton(
            style: style,
            onPressed: null,
            child: const Text('Disabled'),
          ),
          const SizedBox(height: 30),
          ElevatedButton(
            style: style,
            onPressed: () {},
            child: const Text('Enabled'),
          ),
        ],
      ),
    );
  }
}



초기 상태버튼 클릭 (onPressed)

버튼을 누르면 저번에 배워본 InkWell처럼, 누른 지점에서부터 동그라미가 퍼져 나가고 버튼 오른쪽과 아래로 그림자가 생긴다. Disabled는 눌러보아도 아무 반응이 없다.






이번엔 스타일을 좀 적용해보았다. Doit 책의 3단원(76쪽) RaisedButton 예제를 ElevatedButton 으로 바꾸고, style 속성은 출처3의 유튜브를 참고하였다.

import 'package:flutter/material.dart';

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

// ignore: must_be_immutable
class MyApp extends StatefulWidget {
  MyApp();

  
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool switchValue = false;
  String test = 'hello';
  Color _color=Colors.blue;
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity),
      home: Scaffold(
        appBar: AppBar(
          title: Text("Test ElevatedButton"),
        ),
        body: Center(
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(	//모서리를 둥글게
                  borderRadius: BorderRadius.circular(20)),
              primary: _color,
              // onPrimary: Colors.blue,	//글자색
              minimumSize: Size(200, 100),	//width, height
              
              //child 정렬 - 아래의 Text('$test')
              alignment: Alignment.centerLeft,	
              textStyle: const TextStyle(fontSize: 30)
            ),
            child: Text('$test'),
            onPressed: () {
              if (test == 'hello') {
                setState(() {
                  test = 'flutter';
                  _color=Colors.green;
                });
              } else {
                setState(() {
                  test = 'hello';
                  _color=Colors.blue;
                });
              }
            },
          ),
        ),
      ),
    );
  }
}



초기 상태버튼 클릭 (onPressed)

누를때마다 버튼 내부의 글자와 색이 변하는 것을 알 수 있다. 그리고 난 버튼 누를 때 똑 똑 하는 소리가 좋더라..



오늘의 일기는 여기까지!
profile
안 되면 되게 하라

0개의 댓글