Expanded와 Flexible의 차이

다용도리모콘·2022년 1월 17일
0

Wiki - Flutter

목록 보기
6/7

Expanded는 Flexible의 한 타입

매번 구글링 하고나면 '아~'하고 이해한 뒤 금방 잊어버려서 기록해 두는 지식.

//이 코드는
Expanded(
  child: Foo(),
);

//이 코드와 동일함.
Flexible(
  fit: FlexFit.tight,
  child: Foo(),
);
  • FlexFit
    • FlexFit.tight: 가능한 늘어난다.
    • FlexFit.loose: 필요한 만큼 늘어난다.

재미있는 예제

https://stackoverflow.com/questions/65933330/expanded-and-flexible-not-filling-entire-row


  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body:
       Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.max,
            children: [
             // FlexibleWidget(),
              ExpandedWidget(),
              FlexibleWidget(),
            ],
          ),
          Row(
            children: [
              ExpandedWidget(),
              ExpandedWidget(),
            ],
          ),
          Row(mainAxisSize: MainAxisSize.min,
            children: [
              FlexibleWidget(),
              FlexibleWidget(),
            ],
          ),
          Row(mainAxisSize: MainAxisSize.min,
            children: [
              FlexibleWidget(),
              ExpandedWidget(),
            ],
          ),
        ],
     ),
    );
  }
}

class ExpandedWidget extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.green,
          border: Border.all(color: Colors.white),
        ),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            'Expanded',
            style: TextStyle(color: Colors.white, fontSize: 24),
          ),
        ),
      ),
    );
  }
}

class FlexibleWidget extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Flexible(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.red,
          border: Border.all(color: Colors.white),
        ),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            'Flexible',
            style: TextStyle(color: Colors.black, fontSize: 24),
          ),
        ),
      ),
    );
  }
}

  • 2, 3번째 줄의 경우 Expanded는 가능한 늘어나고 Flexible은 필요한 만큼 늘어나니까 예상된 결과이다.
  • 1,4번째 줄의 경우 Expanded가 나머지 영역을 채울만큼 늘어나지 않는다.
    -> Expanded, Flexible 모두 flex라는 부모 안에서 차지할 수 있는 크기의 비례 값을 가지고 있는데 기본값이 1이다. 그렇기 때문에 Row안에 두 위젯이 선언된 순간 각각의 위젯의 최대 크기는 1/2(=50%)로 한정된다. 결과, Expanded는 자신에게 할당된 1/2를 모두 차지하는 크기만큼 늘어나고 Flexible은 1/2 안에서 필요한 만큼만 늘어나게 된 것이다.

0개의 댓글