[flutter] 스택드 위젯을 사용하여 팝업 창 구현하기
이번에는 Flutter 앱에서 팝업 창을 구현하는 방법에 대해 알아보겠습니다. 팝업 창은 앱 사용자에게 정보를 전달하거나 추가적인 작업을 유도할 때 유용하게 활용됩니다. Flutter는 Stack 위젯을 사용하여 다른 위젯들을 겹쳐서 표시할 수 있으므로 이를 이용해서 팝업 창을 구현할 수 있습니다.
1. 팝업 창을 위한 위젯 구성
우선 팝업 창에 표시될 내용을 담은 위젯을 생성합니다. 이 예시에서는 간단한 Container 위젯을 사용하겠습니다.
import 'package:flutter/material.dart';
class PopupContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 200,
color: Colors.white,
child: Center(
child: Text("팝업 내용"),
),
);
}
}
2. Stack 위젯을 사용하여 팝업 창 표시
다음으로, Stack 위젯을 사용하여 화면에 다른 위젯들과 팝업 창을 겹쳐 표시합니다. 팝업 창은 필요할 때 Visibility를 조절하여 보이거나 숨길 수 있도록 해야 합니다.
class PopupExample extends StatefulWidget {
@override
_PopupExampleState createState() => _PopupExampleState();
}
class _PopupExampleState extends State<PopupExample> {
bool _isPopupVisible = false;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
// 화면에 표시될 내용들
// ...
// 팝업 창
Visibility(
visible: _isPopupVisible,
child: Center(
child: PopupContent(),
),
),
],
);
}
}
3. 팝업 창 토글
마지막으로, 팝업 창을 토글하는 기능을 구현합니다. 예제 코드에서는 RaisedButton을 터치했을 때 팝업 창이 나타나거나 사라지도록 하겠습니다.
class _PopupExampleState extends State<PopupExample> {
bool _isPopupVisible = false;
void _togglePopup() {
setState(() {
_isPopupVisible = !_isPopupVisible;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RaisedButton(
onPressed: _togglePopup,
child: Text('팝업 토글'),
),
// ...
// 나머지 화면 내용들
// ...
],
);
}
}
Flutter에서 Stack 위젯을 사용하여 팝업 창을 구현하는 방법에 대해 알아보았습니다. 이를 응용하여 원하는 디자인과 상호작용을 가진 팝업 창을 구현할 수 있습니다.