Flutter
flutter - Snack bar
바차
2021. 7. 20. 02:03
반응형
[Snack bar]
-> 스크린 하단에 간단한 메시지를 띄우는 기능
[ScaffoldMessenger 클래스]
-> 이전 버전에서 사용하던 Scaffold.of(context) method를 사용해서 스낵바를 구현하응 과정이 복잡했었는데 이번에 새롭게 나온 ScaffoldMessenger 위젯을 통해서 간단하게 스낵바를 구현할 수 있다.
[기존 메서드에서의 문제 해결점]
-> 기존 메서드에서 구현한 스낵바는 오직 현재 구현한 페이지 내의 build context 내의 Scaffold 상에서만 구현될 수 있었다.
-> 다른 페이지로 넘어가면 스낵바는 유지되지 못했었다.
-> ScaffoldMessenger 위젯은 MaterialApp같은 위젯 트리 최상위 위치에서 여기저기 흩어져 있는 Scaffold들을 등록해서 언제든 스낵바를 수신할 수 있도록 한 곳에 묶어서 관리 할 수 있도록 해준다.
-> 따라서 이제 더이상 Scaffold에 의해 스낵바가 관리되는 것이 아니라 위젯 트리 최상위 위치의 ScaffoldMessenger에 의해서 관리된다.
[최종 코드]
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Snack Bar',
theme: ThemeData(
primarySwatch: Colors.blue
),
home: MyPage(),
);
}
}
class MyPage extends StatelessWidget {
const MyPage({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold( //ScaffoldMessenger.of 메서드 에서 찾은 가장 가까운 Scaffold를 찾아서 반환
appBar: AppBar(
title: Text('Scaffold Messenger'),
centerTitle: true,
),
body: HomeBody(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.thumb_up),
onPressed: (){
//ScaffoldMessenger.of 메서드 -> 가장 가까운 ScaffoldMessenger를 찾아서 반환하라 라는 뜻
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Like a new Snack bar!'),
duration: Duration(seconds: 4),
action: SnackBarAction(
label: 'Undo',
onPressed: (){
Navigator.push( // 버튼을 눌렀을때 두번째 페이지로 이동하는 구문
context,
MaterialPageRoute(builder: (context) => ThirdPage()),
);
},
),
),
);
},
),
);
}
}
class HomeBody extends StatelessWidget {
const HomeBody({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton( //
child: Text('Go to the Second page'),
onPressed: (){
Navigator.push( // 버튼을 눌렀을때 두번째 페이지로 이동하는 구문
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
},
),
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second page'),
),
body: Center(
child: Text('좋아요가 추가되었습니다.',
style: TextStyle(
fontSize: 20.0,
color: Colors.redAccent
),
),
),
);
}
}
class ThirdPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'좋아요를 취소하시겠습니까?',
style: TextStyle(
fontSize: 20.0,
color: Colors.redAccent
),
),
ElevatedButton(
onPressed: (){
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('좋아요가 취소되었습니다.'),
duration: Duration(seconds: 3),
),
);
},
child: Text('취소하기'),
),
],
),
),
);
}
}
[Fomat Document]
-> 구문 오류가 없는 상태에서 ctrl + alt + f 를 누르면 들여쓰기가 자동으로 되어 편하다.
300x250