※ << 소스코드 #1 >> 과 << 소스 코드 #2 >>의 결과는 동일하고,
단지 SnackBar에서 메세지를 전달하는 BuildContext 인스턴스가 다름.
( << 소스 코드 #2 >>에서는 별도의 BuildContext 인스턴스 ctx를 생성하여 Scaffold로 메세지 전달.
<< 소스 코드 #1 >>
import 'package:flutter/material.dart';
void main() => 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.red
),
home: MyPage(),
);
}
}
class MyPage extends StatelessWidget {
const MyPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Snack Bar'),
centerTitle: true,
),
body: Center(
child: TextButton( //Flutter 2.0에서 FlatButton -> TextButton 변경됨
child: Text(
'Show me',
style: TextStyle(
color: Colors.white, //Text 색상
backgroundColor: Colors.red, //배경색
fontSize: 30.0, //font 사이즈
),
),
onPressed: (){
//Scaffold.of -> ScaffoldMessenger.of 함수로 변경됨.
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Hellow')));
},
),
),
);
}
}
<< 소스 코드 #2 >>
import 'package:flutter/material.dart';
void main() => 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.red
),
home: MyPage(),
);
}
}
class MyPage extends StatelessWidget {
const MyPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Snack Bar'),
centerTitle: true,
),
body: Builder(builder: (BuildContext ctx) {
return Center(
child: TextButton( //Flutter 2.0에서 FlatButton -> TextButton 변경됨
child: Text(
'Show me',
style: TextStyle(
color: Colors.white, //Text 색상
backgroundColor: Colors.red, //배경색
fontSize: 30.0, //font 사이즈
),
),
onPressed: (){
//Scaffold.of -> ScaffoldMessenger.of 함수로 변경됨.
//Scaffold 위젯을 찾기 위해 context(BuildContext)를 찾아 상위 위젯에 텍스트 반환
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Hellow')));
},
),
);
},)
);
}
}
<< 출력 화면 >>
'Flutter (with 코딩셰프)' 카테고리의 다른 글
[2023.11.23] 플러터(flutter) 순한 맛 강좌 19-2 | Toast Message (0) | 2023.11.23 |
---|---|
[2023.11.23] 플러터(flutter) 순한 맛 강좌 19-1 | Snack Bar (without Builder) (0) | 2023.11.23 |
[2023.11.21] 플러터(flutter) 순한 맛 강좌 16 | Drawer Menu #2 (1) | 2023.11.21 |
[2023.11.21] 플러터(flutter) 순한 맛 강좌 15 | Drawer Menu #1 (0) | 2023.11.21 |
[2023.11.20] 플러터(flutter) 순한 맛 강좌 14 | AppBar (1) | 2023.11.20 |