IntrinsicHeight의 역할

pharmDev·2024년 12월 13일

IntrinsicHeight는 Flutter에서 자식 위젯의 높이를 기준으로 부모 위젯의 높이를 조정하는 데 사용됩니다. IntrinsicHeight는 모든 자식 위젯의 고유 높이를 계산하고, 가장 높은 위젯에 맞춰 전체 높이를 결정합니다.

이 위젯은 특히 자식 위젯의 크기가 동적으로 변할 때나, 여러 자식 위젯을 동일한 높이로 맞추고자 할 때 유용합니다. 예를 들어, 열(Column) 내의 자식 위젯들이 다른 크기를 가질 경우, IntrinsicHeight를 사용하면 전체 높이를 조화롭게 정렬할 수 있습니다.


사용법

아래는 IntrinsicHeight를 사용하는 Flutter 예제 코드입니다.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('IntrinsicHeight 예제')),
        body: Center(
          child: IntrinsicHeight(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Expanded(
                  child: Container(
                    color: Colors.blue,
                    child: Text(
                      '짧은 텍스트',
                      style: TextStyle(color: Colors.white),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    color: Colors.green,
                    child: Text(
                      '여기에는 조금 더 긴 텍스트가 들어갑니다.',
                      style: TextStyle(color: Colors.white),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

코드 설명

  1. IntrinsicHeightRow를 감싸고 있습니다.
  2. Row 내부의 각 컨테이너의 높이는 텍스트의 내용에 따라 다를 수 있지만, IntrinsicHeight를 사용하면 모든 자식의 높이가 동일하게 조정됩니다.
  3. crossAxisAlignment: CrossAxisAlignment.stretch를 사용해 Row의 자식들이 세로로 맞춰지도록 설정했습니다.

언제 사용해야 할까?

  • 자식 위젯들의 높이가 불균형할 때, 이를 균일하게 맞추고 싶을 때.
  • 텍스트나 위젯의 내용 길이에 따라 레이아웃이 불균형해질 수 있는 경우.
  • 고정된 높이가 아닌, 동적으로 변하는 레이아웃을 조정하고 싶을 때.

주의사항

  • IntrinsicHeight는 퍼포먼스 비용이 조금 있을 수 있습니다. 복잡한 UI에 남용하지 않도록 주의하세요.
profile
코딩을 배우는 초보

0개의 댓글