Mediaquery vs Layoutbuilder에 대해 비교

열심이·2023년 4월 10일

Flutter에서는 레이아웃 구성을 위해 MediaQuery와 LayoutBuilder라는 두 가지 유틸리티 클래스가 제공됩니다.

MediaQuery는 현재 장치의 미디어 쿼리 정보를 제공하는 클래스입니다. 이 클래스를 사용하면 현재 디바이스의 크기, 방향, 해상도 등과 같은 정보를 얻을 수 있습니다. 이 정보를 사용하여 레이아웃을 조정하고, 반응형 디자인을 구현할 수 있습니다.

예를 들어, 다음 코드는 현재 디바이스의 높이와 너비를 출력하는 방법을 보여줍니다.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final Size screenSize = MediaQuery.of(context).size;
    final double screenHeight = screenSize.height;
    final double screenWidth = screenSize.width;

    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('Screen width: $screenWidth\nScreen height: $screenHeight'),
        ),
      ),
    );
  }
}

LayoutBuilder는 위젯의 크기 및 위치 정보를 제공하는 클래스입니다. 이 클래스를 사용하면 부모 위젯의 크기가 변경될 때마다 자식 위젯의 레이아웃을 조정할 수 있습니다.

예를 들어, 다음 코드는 부모 위젯의 너비와 높이를 출력하는 방법을 보여줍니다.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            final double height = constraints.maxHeight;
            final double width = constraints.maxWidth;
            return Center(
              child: Text('Parent width: $width\nParent height: $height'),
            );
          },
        ),
      ),
    );
  }
}

결론적으로, MediaQuery는 현재 디바이스의 미디어 쿼리 정보를 제공하며, LayoutBuilder는 부모 위젯의 크기 정보를 제공합니다. 두 클래스를 사용하여 반응형 디자인을 구현하고 레이아웃을 조정할 수 있습니다.

profile
열심이하는자

0개의 댓글