Flutter - #38. MediaQuery

Pearl Lee·2021년 8월 19일
0

Flutter Widget

목록 보기
36/50

Flutter 일기
참고 1: https://api.flutter.dev/flutter/widgets/MediaQuery-class.html








MediaQuery

오늘 배워볼 것은 MediaQuery
기기의 화면 너비나 높이를 가져오거나, 화면 방향 정보(가로/세로)를 얻을 때 주로 쓴다. 다른 용도로 쓰는 건 거의 목격하지 못했으므로! 요걸 중점적으로 다뤄보도록 하겠다.

늘 이걸로 일기 써봐야지 하다가 애뮬레이터에서 헤매는 바람에 ^^ 이제 쓴다.

애뮬레이터 화면 전환 활성화해줘야 합니다 ^^
LayoutBuilder때는 어떻게 한걸까...









코드 예시로 알아보자

공식 페이지 예제가 없어서 그냥 간단하게 만들었다.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test MediaQuery',
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    MediaQueryData deviceData = MediaQuery.of(context);
    Size screenSize = deviceData.size;

    return Scaffold(
      appBar: AppBar(
        title: Text('Test MediaQuery'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Device width : ${screenSize.width.toInt()}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 20,
            ),
            Text(
              'Device height : ${screenSize.height.toInt()}',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 20,
            ),
            // deviceData.orientation == Orientation.portrait
            screenSize.width > 500
                ? Container(
                    width: screenSize.width / 5,
                    height: screenSize.height / 2,
                    color: Colors.amber.withOpacity(.5),
                  )
                : Container(
                    width: screenSize.width / 3,
                    height: screenSize.height / 3,
                    color: Colors.red.withOpacity(.5),
                  ),
          ],
        ),
      ),
    );
  }
}




우선 실행화면을 먼저 보면 다음과 같다.

screenSize.width < 500 또는 Orientation.portraitscreenSize.width > 500 또는 Orientation.landscape

세로 화면일 때는 화면 너비가 411 이 나오는데, 가로화면으로 전환하면 771이 나오게 된다. 그래서 screenSize.width 가 500을 넘어가면 노란색 컨테이너를 띄우도록 해보았다.

그런데 이거 말고 orientation 으로 전환 조건을 설정해도 된다.
portraite : 가로 | landscape : 세로 이다.





이것만 놓고 보면 LayoutBuilder 와 기능이 거의 똑같은데, 플러터 3개월 배우는 동안 MediaQuery가 아니라 LayoutBuilder를 쓰는 경우는 거의 못봤다. 공식페이지에서도 MediaQuery가 좀 더 낫다고 함... LayoutBuilder가 사이즈 요청하는 간단한 버전이라고 한다. 그냥 거의 다 MediaQuery쓴다는 것만 알고 넘어가면 될 듯


오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글