[Flutter Layout] AspectRatio

김기현·2025년 3월 5일

Flutter Layout

목록 보기
2/8

Flutter 공식 AspectRatio

앱을 배치할때 종횡비를 신경쓴다.
실제 크기와 관계없이 위젯이 특정한 넓이를 가지도록 하기를 원한다.
얇거나 정사각형이 되거나 하는식으로

AspectRatio(
	aspectRatio : 3/2, //1.5로 사용해도 무방하다.
    child : MyWidget(),
)

AspectRatio는 상자의 너비와 높이의 비율이다.
3/2처럼 분수로 표현한다. 너비/높이
하위요소는 어떤것이든 가능하다. (예를 들면 Container, 이미지, 전체위젯트리 등)
AspectRatio위젯이 하위요소의 크기를 표시하도록 해야한다.
AspectRatio를 Expanded같은 곳에 두게 되면 상위요소가 확장을 강요하게된다.
따라서 Expanded같은 타이트한 규모의 위젯은 하위요소에 선택권을 주지 않는다. 이런일이 발생할 때엔 Expanded와 AspecRatio 사이에 선같은 걸 배치해보자

Expanded(
	child: Align(
    	alignment: Alignment.bottomCenter,
        child: AspectRatio(
        	aspectRatio: 3/2,
            child: MyWidget(),
        ),
    ),
)

선은 Expanded로 인해 영역을 채우도록 강요될 것이지만 하위요소가 비율을 조정하도록 내버려둔다.

AspectRatio 위젯은 유한 반복 프로세스를 사용하여 자식에게 적합한 제약 조건을 계산한 다음, 이러한 제약 조건으로 자식을 한번만 배치한다.
처음엔 레이아웃에서 가장 넓은 너비를 적용하고 종횡비에 맞춰 높이를 맞춘다.

만약 넓이가 무한하다면 위의 방법과 똑같이 높이를 기준으로 종횡비를 맞춘다.
그리고 부모의 제약에 맞는지 검사한다. 그렇지 않다면 다시한번 계산한다.

아무리해도 종횡비를 찾지 못한다면 위젯은 제약조건은 만족하지만 종횡비는 충족하지 못하는 자식의 크기를 선택한다.

align을 지우고 실행했으나 위치를 제외하곤 다른점을 잘 모르겠다

import 'package:flutter/material.dart';

/// Flutter code sample for [AspectRatio].

void main() => runApp(const AspectRatioApp());

class AspectRatioApp extends StatelessWidget {
  const AspectRatioApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('AspectRatio Sample')),
        body: const AspectRatioExample(),
      ),
    );
  }
}

class AspectRatioExample extends StatelessWidget {
  const AspectRatioExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      alignment: Alignment.center,
      width: double.infinity,
      height: 100.0,
      child: AspectRatio(aspectRatio: 16 / 9, child: Container(color: Colors.green)),
    );
  }
}

그리 어려워보이지 않아 예제하나 적고 마무리

Constructors

AspectRatio({Key? key, required double aspectRatio, Widget? child})

Properties

  • aspectRatio(double)
    - 종횡비
  • child(Widget?)
    - 자식 위젯들

0개의 댓글