'플러터 팝업창'에 해당되는 글 1건

728x90

특정 버튼(이미지, List Item 등)을 눌렀을 때 팝업되는 메시지 구현 예제이다.

import 'package:flutter/material.dart';
 
class LView extends StatefulWidget {
  const LView({Key? key, required this.title}) : super(key: key);
 
  final String title; // 부모 위젯으로부터 전달받은 변수
 
  @override
  State<LView> createState() => _LViewState();
}
 
class _LViewState extends State<LView> {
  var name = ['강감찬''홍길동''이순신','유관순'];
  var clickme = [0000];
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
         itemCount: name.length,
          itemBuilder: (c, i) {
            return ListTile(
              leading: Text(clickme[i].toString()),
              title: Text(name[i]),
              trailing: ElevatedButton(
                child: Text('좋아요'),
                onPressed: () {
                  setState(() {
                    clickme[i]++;
                  });
                },
              ),
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ShowDialog(),
        // child: Text(_counter.toString()),
        child: const Icon(Icons.add),
      ),
    );
  }
 
  ShowDialog() {
    showDialog<String>(
        context: context,
        barrierDismissible: false// Dialog를 제외한 다른 화면 터치 x
        builder: (BuildContext context) {
          return AlertDialog(
            // RoundedRectangleBorder - Dialog 화면 모서리 둥글게 조절
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0)),
            backgroundColor: Colors.white,
            //Dialog Main Title
            title: Column(
              children: <Widget>[
                Text("팝업 메시지"),
              ],
            ),
            //
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  "AlertDialog Content",
                ),
              ],
            ),
            actions: <Widget>[
              ElevatedButton(
                onPressed: () => Navigator.pop(context, 'Cancel'),
                child: const Text('Cancel'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context, 'OK'),
                child: const Text('OK'),
              ),
            ],
          );
        });
  }
}
 

 

값을 넘겨주는 걸 처리하는 방법에 대해 알아보자.

부모 위젯 → 자식 위젯 으로 값을 넘기는 방법

Class 간에 값 전달 방식으로 값, 함수를 넘기므로 아래 코드에서 해당 주석 부분을 잘 살펴보면 된다.

import 'package:flutter/material.dart';
 
class LView extends StatefulWidget {
  const LView({Key? key, required this.title}) : super(key: key);
 
  final String title; // 부모 위젯으로부터 전달받은 변수
 
  @override
  State<LView> createState() => _LViewState();
}
 
class _LViewState extends State<LView> {
  var name = ['강감찬''홍길동''이순신','유관순'];
  var clickme = [0000];
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
         itemCount: name.length,
          itemBuilder: (c, i) {
            return ListTile(
              leading: Text(clickme[i].toString()),
              title: Text(name[i]),
              trailing: ElevatedButton(
                child: Text('좋아요'),
                onPressed: () {
                  setState(() {
                    clickme[i]++;
                  });
                },
              ),
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: () => showDialog<String>(
            context: context,
            barrierDismissible: false// Dialog를 제외한 다른 화면 터치 x
            builder: (context){
          return DialogUI(Cnt: clickme[1], Name: name[1]); // 변수 넘겨주기
        }),
        // child: Text(_counter.toString()),
        child: const Icon(Icons.add),
      ),
    );
  }
 
}
 
class DialogUI extends StatelessWidget {
  const DialogUI({Key? key, this.Cnt, this.Name}) : super(key: key);
  final Cnt; // 부모 위젯으로부터 전달받은 변수 등록
  final Name; // 부모 위젯으로부터 전달받은 변수 등록
 
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      // RoundedRectangleBorder - Dialog 화면 모서리 둥글게 조절
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0)),
      backgroundColor: Colors.white,
      //Dialog Main Title
      title: Column(
        children: <Widget>[
          Text("팝업 메시지"),
        ],
      ),
      //
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "AlertDialog Content : 카운트 횟수 ${Cnt}, 이름 : ${Name}",
          ),
        ],
      ),
      actions: <Widget>[
        ElevatedButton(
          onPressed: () => Navigator.pop(context, 'Cancel'),
          child: const Text('Cancel'),
        ),
        ElevatedButton(
          onPressed: () => Navigator.pop(context, 'OK'),
          child: const Text('OK'),
        ),
      ],
    );
  }
}

 

이제 ListView Item 에서 클릭을 하면 팝업창이 뜨는 예제로 전환해보자.

title : Text 를 title : TextButton 으로 변경하고 onPressed 이벤트를 추가한다.

import 'package:flutter/material.dart';
 
class LView extends StatefulWidget {
  const LView({Key? key, required this.title}) : super(key: key);
 
  final String title; // 부모 위젯으로부터 전달받은 변수
 
  @override
  State<LView> createState() => _LViewState();
}
 
class _LViewState extends State<LView> {
  var name = ['강감찬''홍길동''이순신','유관순'];
  var clickme = [0000];
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
         itemCount: name.length,
          itemBuilder: (c, i) {
            return ListTile(
              leading: Text(clickme[i].toString()),
              title: TextButton(
                  child: Text(name[i]),
                onPressed: () => showDialog<String>(
                    context: context,
                    barrierDismissible: false// Dialog를 제외한 다른 화면 터치 x
                    builder: (context){
                      return DialogUI(Cnt: clickme[i], Name: name[i]); // 변수 넘겨주기
                    }),
              ),
              trailing: ElevatedButton(
                child: Text('좋아요'),
                onPressed: () {
                  setState(() {
                    clickme[i]++;
                  });
                },
              ),
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: (){},
        child: const Icon(Icons.add),
      ),
    );
  }
 
}
 
class DialogUI extends StatelessWidget {
  const DialogUI({Key? key, this.Cnt, this.Name}) : super(key: key);
  final Cnt; // 부모 위젯으로부터 전달받은 변수 등록
  final Name; // 부모 위젯으로부터 전달받은 변수 등록
 
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      // RoundedRectangleBorder - Dialog 화면 모서리 둥글게 조절
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0)),
      backgroundColor: Colors.white,
      //Dialog Main Title
      title: Column(
        children: <Widget>[
          Text("팝업 메시지"),
        ],
      ),
      //
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "카운트 횟수 ${Cnt}, 이름 : ${Name}",
          ),
        ],
      ),
      actions: <Widget>[
        ElevatedButton(
          onPressed: () => Navigator.pop(context, 'Cancel'),
          child: const Text('Cancel'),
        ),
        ElevatedButton(
          onPressed: () => Navigator.pop(context, 'OK'),
          child: const Text('OK'),
        ),
      ],
    );
  }
}
 

 

 

'Flutter 앱 > Flutter Basic' 카테고리의 다른 글

Flutter Widget 개념(stateless, stateful)  (0) 2022.06.18
Flutter input dialog (자식 → 부모)  (0) 2022.06.15
Flutter ListView 예제1  (0) 2021.12.27
Flutter Toast 메시지  (0) 2021.12.24
Flutter 화면 이동 (Navigator)  (0) 2021.12.23
블로그 이미지

Link2Me

,