flutter(플러터) - 07. 미디어 쿼리와 빌드컨텍스트(MediaQuery, BuildContext)

JungSik Heo·2026년 4월 29일

flutter

목록 보기
7/23

Flutter MediaQuery & BuildContext 예제 정리

📌 1. 개념 먼저

✅ BuildContext

  • 현재 위젯의 위치(트리 상 위치)를 알려주는 객체
  • 위젯 트리에서 부모/환경 정보 접근할 때 사용

👉 대표 사용

Theme.of(context)
MediaQuery.of(context)
Navigator.of(context)

✅ MediaQuery

  • 화면 크기, 방향, 패딩 등 디바이스 정보 제공

👉 대표 정보

  • 화면 너비 / 높이
  • 상태바 / 노치 영역
  • 가로 / 세로 모드

📌 2. 핵심 예제 (한 파일)

👉 화면 크기 기반 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("뒤로가기"),
            ),
          ],
        ),
      ),
    );
  }
}

📌 3. 핵심 포인트

🔹 MediaQuery

final size = MediaQuery.of(context).size;

👉 화면 크기 가져오기


MediaQuery.of(context).padding.top

👉 상태바 / 노치 높이


🔹 BuildContext

Navigator.of(context).push(...)

👉 화면 이동


Theme.of(context)

👉 테마 접근


📌 4. 실무 핵심 패턴

✅ 반응형 UI

width: MediaQuery.of(context).size.width * 0.8

👉 디바이스마다 자동 대응


✅ 방향 감지

if (width > height) {
  // 가로 모드
}

🚨 주의 (중요)

❌ initState에서 MediaQuery 사용

void initState() {
  MediaQuery.of(context); // ❌ 에러 가능
}

👉 이유: context 아직 준비 안됨


✅ 해결


void didChangeDependencies() {
  super.didChangeDependencies();
  MediaQuery.of(context); // ✅ 가능
}

📌 5. 한 줄 정리

👉 BuildContext는 위치, MediaQuery는 화면 정보


🚀 추가 팁

  • 반응형 UI = MediaQuery 필수
  • context는 "위젯 트리 접근 열쇠"
  • Navigator / Theme / MediaQuery 전부 context 기반

profile
쿵스보이(얼짱뮤지션)

0개의 댓글