본문 바로가기
Flutter/Widget

플러터 OrientationBuilder 가이드: 화면 회전에 따른 레이아웃 변경

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

 

플러터(Flutter)는 반응형 사용자 인터페이스(UI)를 구축하는 데 탁월한 도구입니다.

특히, OrientationBuilder 위젯을 사용하면 화면의 가로 및 세로 방향(orientation)에 따라 레이아웃을 동적으로 변경할 수 있습니다.

이번 포스트에서는 Flutter의 OrientationBuilder 위젯의 사용법과 주요 옵션에 대해 알아보겠습니다.

OrientationBuilder 위젯이란?

OrientationBuilder 위젯은 현재 화면의 방향(세로 또는 가로)에 따라 다른 레이아웃을 제공할 수 있도록 해줍니다.

사용자가 디바이스를 회전할 때, OrientationBuilder는 방향을 감지하고, 이에 맞는 레이아웃을 동적으로 렌더링합니다.

OrientationBuilder 위젯 기본 사용법

OrientationBuilder 위젯은 builder 함수를 통해 현재 화면의 방향에 따라 위젯을 구성할 수 있습니다.

builder 함수는 두 개의 매개변수를 사용합니다:

  • context: 현재 빌드 컨텍스트.
  • orientation: 현재 화면의 방향을 나타내는 Orientation 값(Orientation.portrait 또는 Orientation.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('OrientationBuilder Example')),
        body: OrientationBuilder(
          builder: (context, orientation) {
            return GridView.count(
              crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
              children: List.generate(8, (index) {
                return Container(
                  margin: EdgeInsets.all(10),
                  color: Colors.blue,
                  child: Center(
                    child: Text(
                      'Item $index',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                  ),
                );
              }),
            );
          },
        ),
      ),
    );
  }
}

 

위 코드에서는 화면이 세로일 때는 2개의 열, 가로일 때는 3개의 열로 구성된 그리드 뷰를 보여줍니다.

OrientationBuilder가 현재 화면 방향을 감지하여 그에 맞는 레이아웃을 자동으로 조정합니다.

OrientationBuilder를 사용하는 이유

  • 반응형 디자인: 다양한 화면 크기와 방향에 따라 UI를 동적으로 변경하여 사용자 경험을 향상시킬 수 있습니다.
  • 장치 호환성: OrientationBuilder를 사용하면 다양한 디바이스에서 일관된 UI를 유지할 수 있습니다.
  • 유연성: OrientationBuilder는 조건부 레이아웃 변경에 대한 강력한 유연성을 제공합니다.

OrientationBuilder와 MediaQuery 비교

OrientationBuilder와 유사한 역할을 하는 Flutter의 MediaQuery 클래스도 있습니다.

MediaQuery는 화면의 전체적인 정보(예: 크기, 방향, 패딩 등)를 제공하는 반면, OrientationBuilder는 방향에 특화된 위젯입니다.

복잡한 레이아웃이나 추가적인 환경 정보를 필요로 하는 경우 MediaQuery를 함께 사용할 수 있습니다.

MediaQuery를 사용하는 방법

import 'package:flutter/material.dart';

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

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

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('MediaQuery Example')),
        body: GridView.count(
          crossAxisCount: orientation == Orientation.portrait ? 2 : 4,
          children: List.generate(8, (index) {
            return Container(
              margin: EdgeInsets.all(10),
              color: Colors.red,
              child: Center(
                child: Text(
                  'Item $index',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
              ),
            );
          }),
        ),
      ),
    );
  }
}

OrientationBuilder 사용 시 주의사항

  • 레이아웃 복잡성: OrientationBuilder는 간단한 레이아웃 변경에 유용하지만, 너무 복잡한 레이아웃에서는 오히려 가독성을 떨어뜨릴 수 있습니다.
  • 성능 고려: 방향에 따라 전체 레이아웃을 재구성해야 하는 경우, 성능에 미치는 영향을 고려하여 효율적인 방법을 사용해야 합니다.

 

OrientationBuilder 위젯은 Flutter에서 화면의 방향에 따라 유연하게 레이아웃을 변경할 수 있는 강력한 도구입니다.

이를 활용하여 다양한 화면 크기와 방향에 대응하는 반응형 UI를 쉽게 구축할 수 있습니다.

Flutter로 다양한 장치에서 일관된 사용자 경험을 제공하고자 한다면, OrientationBuilder를 꼭 활용해 보세요!

공감과 댓글은 저에게 큰 힘이 됩니다.

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

 

 

반응형