본문 바로가기
Flutter

플러터에서 MediaQuery와 Orientation 사용법: 초보자도 쉽게 이해할 수 있는 가이드

by Maccrey Coding 2024. 8. 6.
반응형

 

안녕하세요, 개발자 여러분!

오늘은 Flutter에서 화면 크기와 방향을 다루는 중요한 도구인 MediaQuery와 Orientation에 대해 쉽게 설명해드릴게요. 이 두 가지는 모바일 앱의 반응형 디자인을 구현하는 데 필수적인 요소입니다.

초보자도 쉽게 이해할 수 있도록 단계별로 설명하겠습니다.

1. Flutter MediaQuery란?

MediaQuery는 Flutter 애플리케이션에서 디바이스의 화면 크기, 해상도, 방향 등의 정보를 제공하는 위젯입니다.

이를 통해 다양한 화면 크기와 해상도에 맞게 앱을 디자인할 수 있습니다.

사용 예제

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('MediaQuery 예제')),
        body: MediaQueryExample(),
      ),
    );
  }
}

class MediaQueryExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // MediaQuery를 통해 화면 크기 정보를 얻습니다.
    final mediaQuery = MediaQuery.of(context);
    final screenWidth = mediaQuery.size.width;
    final screenHeight = mediaQuery.size.height;

    return Center(
      child: Container(
        width: screenWidth * 0.8,
        height: screenHeight * 0.5,
        color: Colors.blue,
        child: Center(
          child: Text(
            '화면 크기: ${screenWidth.toStringAsFixed(2)} x ${screenHeight.toStringAsFixed(2)}',
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
      ),
    );
  }
}

위 코드에서 MediaQuery.of(context)를 사용하여 화면의 너비와 높이를 가져와서 사용하고 있습니다.

이를 통해 화면 크기에 따라 동적으로 UI를 조절할 수 있습니다.

2. Flutter Orientation이란?

Orientation은 화면의 방향을 나타냅니다. 일반적으로 두 가지 방향이 있습니다:

  • 세로 방향 (Portrait): 화면의 높이가 너비보다 큽니다.
  • 가로 방향 (Landscape): 화면의 너비가 높이보다 큽니다.

사용 예제

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Orientation 예제')),
        body: OrientationExample(),
      ),
    );
  }
}

class OrientationExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final orientation = MediaQuery.of(context).orientation;

    return Center(
      child: Container(
        width: orientation == Orientation.portrait ? 200 : 400,
        height: orientation == Orientation.portrait ? 400 : 200,
        color: Colors.red,
        child: Center(
          child: Text(
            '현재 방향: ${orientation == Orientation.portrait ? '세로' : '가로'}',
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
      ),
    );
  }
}

위 코드에서는 MediaQuery.of(context).orientation을 사용하여 현재 화면 방향을 확인하고, 방향에 따라 Container의 크기를 조절하고 있습니다.

3. MediaQuery와 Orientation을 활용한 반응형 디자인

MediaQuery와 Orientation을 활용하면 다양한 화면 크기와 방향에 맞게 앱을 디자인할 수 있습니다.

예를 들어, 화면 크기에 따라 레이아웃을 변경하거나, 화면 방향에 따라 다른 UI를 표시할 수 있습니다.

예제: 화면 크기에 따라 다른 레이아웃 적용

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('반응형 디자인 예제')),
        body: ResponsiveLayout(),
      ),
    );
  }
}

class ResponsiveLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final isLargeScreen = mediaQuery.size.width > 600;

    return Center(
      child: isLargeScreen
          ? Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(width: 200, height: 200, color: Colors.green),
                SizedBox(width: 20),
                Container(width: 200, height: 200, color: Colors.orange),
              ],
            )
          : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(width: 200, height: 200, color: Colors.green),
                SizedBox(height: 20),
                Container(width: 200, height: 200, color: Colors.orange),
              ],
            ),
    );
  }
}

위 코드에서는 화면 너비가 600 픽셀을 넘으면 Row로 배치하고, 그렇지 않으면 Column으로 배치하여 반응형 레이아웃을 구현하고 있습니다.

마무리

오늘은 Flutter의 MediaQuery와 Orientation을 사용하여 화면 크기와 방향에 따라 앱의 UI를 조절하는 방법을 알아보았습니다.

이 두 가지를 잘 활용하면 다양한 디바이스에서 일관된 사용자 경험을 제공할 수 있습니다.

앞으로의 프로젝트에서도 유용하게 활용해보세요!

다음 포스팅에서도 유용한 Flutter 팁과 트릭을 가져올 예정이니 많은 기대 부탁드려요!

 

Starting Google Play App Distribution! "Tester Share" for Recruiting 20 Testers for a Closed Test.

 

Tester Share [테스터쉐어] - Google Play 앱

Tester Share로 Google Play 앱 등록을 단순화하세요.

play.google.com

반응형