[flutter] 플러터(Flutter)에서 기기 방향 변경 감지 및 처리 방법은?

플러터(Flutter) 앱을 개발할 때, 기기의 방향 변경에 따라 화면을 동적으로 조정해야 하는 경우가 있습니다. 예를 들어, 기기를 세로 방향에서 가로 방향으로 회전할 때 화면 레이아웃을 변경해야 하는 상황이 그 예입니다. 이때, 플러터에서는 기기의 방향 변경을 감지하고 이에 대한 처리를 구현할 수 있습니다.

기기 방향 변경 감지

플러터에서는 OrientationBuilder 위젯을 사용하여 기기의 방향 변경을 감지할 수 있습니다. 이 위젯을 활용하면 기기가 세로 또는 가로로 회전할 때마다 화면을 다시 그릴 수 있습니다.

예를 들어, 다음 코드는 OrientationBuilder를 사용하여 기기의 방향에 따라 다른 UI를 표시하는 예제입니다.

import 'package:flutter/material.dart';

class OrientationDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return OrientationBuilder(
      builder: (context, orientation) {
        return orientation == Orientation.portrait
            ? Container(
                child: Center(
                  child: Text('세로 방향'),
                ),
              )
            : Container(
                child: Center(
                  child: Text('가로 방향'),
                ),
              );
      },
    );
  }
}

void main() => runApp(MaterialApp(home: OrientationDemo()));

위 코드에서는 OrientationBuilder를 사용하여 orientation 값에 따라 세로 방향일 때와 가로 방향일 때 다른 UI를 보여주고 있습니다.

방향 변경 처리

기기의 방향이 변경될 때마다 특정 작업을 수행하려면 OrientationBuilder를 활용하여 해당 작업을 수행하는 함수를 호출하면 됩니다. 예를 들어, 방향이 변경될 때마다 화면을 갱신하거나 다른 작업을 실행하고자 할 때는 setState 메서드를 활용하여 화면을 다시 그리는 방식으로 처리할 수 있습니다.

import 'package:flutter/material.dart';

class OrientationDemo extends StatefulWidget {
  @override
  _OrientationDemoState createState() => _OrientationDemoState();
}

class _OrientationDemoState extends State<OrientationDemo> {
  @override
  Widget build(BuildContext context) {
    return OrientationBuilder(
      builder: (context, orientation) {
        return Center(
          child: RaisedButton(
            child: Text('화면 갱신'),
            onPressed: () {
              setState(() {
                // 방향 변경 시 수행할 작업 수행
              });
            },
          ),
        );
      },
    );
  }
}

void main() => runApp(MaterialApp(home: OrientationDemo()));

위 코드에서는 setState 메서드를 호출하여 방향 변경 시 원하는 작업을 수행하도록 처리하고 있습니다.

플러터에서는 OrientationBuildersetState 메서드를 활용하여 기기의 방향 변경을 감지하고 처리하는 방법을 제공하고 있습니다.

참고 자료