👉 대표 사용
Theme.of(context)
MediaQuery.of(context)
Navigator.of(context)
👉 대표 정보
👉 화면 크기 기반 UI + context 활용
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
Widget build(BuildContext context) {
return const MaterialApp(
home: MediaQueryExample(),
);
}
}
class MediaQueryExample extends StatelessWidget {
const MediaQueryExample({super.key});
Widget build(BuildContext context) {
// 📌 MediaQuery 사용
final size = MediaQuery.of(context).size;
final width = size.width;
final height = size.height;
final isLandscape = width > height;
return Scaffold(
appBar: AppBar(title: const Text("MediaQuery Example")),
body: Column(
children: [
// 📊 화면 정보 표시
Text("width: $width"),
Text("height: $height"),
Text("가로 모드: $isLandscape"),
const SizedBox(height: 20),
// 📌 반응형 박스
Container(
width: width * 0.8,
height: 100,
color: Colors.blue,
child: const Center(
child: Text("화면 너비의 80%"),
),
),
const SizedBox(height: 20),
// 📌 버튼 → Navigator (context 사용)
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const SecondPage(),
),
);
},
child: const Text("다음 화면"),
),
],
),
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({super.key});
Widget build(BuildContext context) {
final padding = MediaQuery.of(context).padding;
return Scaffold(
appBar: AppBar(title: const Text("Second Page")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("상태바 높이: ${padding.top}"),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text("뒤로가기"),
),
],
),
),
);
}
}
final size = MediaQuery.of(context).size;
👉 화면 크기 가져오기
MediaQuery.of(context).padding.top
👉 상태바 / 노치 높이
Navigator.of(context).push(...)
👉 화면 이동
Theme.of(context)
👉 테마 접근
width: MediaQuery.of(context).size.width * 0.8
👉 디바이스마다 자동 대응
if (width > height) {
// 가로 모드
}
void initState() {
MediaQuery.of(context); // ❌ 에러 가능
}
👉 이유: context 아직 준비 안됨
void didChangeDependencies() {
super.didChangeDependencies();
MediaQuery.of(context); // ✅ 가능
}
👉 BuildContext는 위치, MediaQuery는 화면 정보