Flutter - #23. AlertDialog

Pearl Lee·2021년 6월 25일
0

Flutter Widget

목록 보기
22/50

내가 보려고 쓰는 Flutter 일기
참고1 : https://api.flutter.dev/flutter/material/AlertDialog-class.html
참고2 : https://api.flutter.dev/flutter/material/showDialog.html







AlertDialog

오늘 배울 위젯은 AlertDialog
사용자에게 알림을 띄우거나, 사용자의 입력 값을 받아야 할 때 사용하는 대화 상자이다. 팝업 창 형태로 뜨고, 크게 제목(title), 내용(content), 선택값(actions) 으로 구성되어 있다. content에는 글이나 그림을 넣어도 되고, actions에는 버튼들을 넣어 클릭 이벤트를 구현할 수 있다.
그리고 Dialog Box를 띄워주는 showDialog와 함께 쓴다.








코드 예시로 알아보자

오늘도 공식 페이지의 코드를 가져다가 ListTile을 추가해서 돌려보았다.
ListTile을 누르면 Dialog가 뜨고, Yes버튼을 누르면 ListTile의 완료 항목이 변경되는 형태이다.

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 = 'Test AlertDialog';

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

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

  
  _MyAlertDialogState createState() => _MyAlertDialogState();
}

class _MyAlertDialogState extends State<MyAlertDialog> {
  bool isCompleted = false;

  
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          children: [
            ListTile(
                title: Text(
                  '공부하기',
                  style: TextStyle(fontSize: 50),
                ),
                subtitle: Container(
                  child: Column(children: [
                    Text(
                      '완료 : ${isCompleted == true ? 'True' : 'False'}',
                      style: TextStyle(fontSize: 30),
                    ),
                    Container(
                      height: 1,
                      color: Colors.blue,
                    )
                  ]),
                ),
                onTap: () {
                  showDialog<String>(
                    context: context,
                    builder: (BuildContext context) => AlertDialog(
                      title: const Text('AlertDialog'),
                      content: const Text('완료 상태를 바꾸시겠습니까?'),
                      actions: <Widget>[
                        TextButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: const Text('No'),
                        ),
                        TextButton(
                          onPressed: () {
                            setState(() {
                              isCompleted == true
                                  ? isCompleted = false
                                  : isCompleted = true;
                            });
                            Navigator.of(context).pop();
                          },
                          child: const Text('Yes'),
                        ),
                      ],
                    ),
                  );
                })
          ],
        ),
      ),
    );
  }
}

ListTile의 subtitle속성에 설정한, '완료:True' 요 위젯이 변경된다.
ListTile의 onTap속성에 showDialog를 만들어서, AlertDialog가 보여지도록 해주었다. 실행화면은 아래와 같다.









Dialogbox의 스타일을 변경할 수도 있다. 쓸 일이 많을 거 같진 않지만... actions:[] 아래에 코드를 추가해 보았다.

elevation: 20,
titleTextStyle: TextStyle(color: Colors.white,fontSize: 20),
contentTextStyle: TextStyle(color: Colors.white,fontSize: 15),
backgroundColor: Colors.black54,
코드 추가 전코드 추가 후

title, content에 TextStyle을 설정하고, 배경을 검정색으로 바꾸고, Dialog가 뜰 때 뒤로 그림자가 생기게 하였다. 저 Yes No 버튼 글자색을 바꾸려면 TextButton에서 따로 설정해야한다.




오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글