Flutter - #35. ConstrainedBox

Pearl Lee·2021년 7월 27일
0

Flutter Widget

목록 보기
33/50

Flutter 일기
출처 : https://api.flutter.dev/flutter/widgets/ConstrainedBox-class.html









ConstrainedBox

오늘 배워볼 것은 ConstrainedBox.
constrain 은 강요하다, 제약하다 정도로 해석하므로, 자식 요소에 추가적인 제약 요소를 두는 것이다.
자식 위젯의 너비나 높이의 최댓값, 최솟값을 설정할 수 있다.









코드 예시로 알아보자

  1. 먼저 Text 위젯에 적용했을 때, 어떻게 되는지 살펴보자. 공식 유튜브에 나오는 위젯을 가져다가 돌려보았다.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test ConstrainedBox"),
      ),
      body: Center(
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: 200
          ),
          child: Text('Delicious Candy',
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 20),),
        ),
      ),
    );
  }
}

Text 위젯을 ConstrainedBox 로 감싸고, 최대 너비를 200으로 주었다.
Text 위젯의 fontSize가 일정 크기 이상 커지면, 최대 너비 200을 벗어나지 못해 한 줄로 쓰여진 문구가 두 줄로 바뀐다.
실행화면을 보자.

fontSize: 20fontSize: 30

fontSize가 커지니 최대 너비 제한에 걸려서, Text가 두 줄로 나뉘어지는 것을 볼 수 있다.










2. 이번엔 child 를 ElevatedButton으로 바꿔보자.

child: ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: 200
          ),
          child: ElevatedButton(
            child: Text("I'm a Button",style: TextStyle(fontSize: 30),),
            onPressed: () { },
          )
        ),
minHeight: 100minHeight: 200









constraints 속성에 다른 것도 넣어보자

BoxConstraints.tightFor({double? width, double? height})

constraints: BoxConstraints.tightFor(width : 100, height: 200),

인자로 받는 너비와 높이값만큼 자식 위젯의 크기를 그려준다.
인자 안넣으면 자식 요소 너비, 높이를 결정하지 않아 최소한의 크기만 갖는.. 것 같다.

BoxConstraints.expand({double? width, double? height})

 constraints: BoxConstraints.expand(),

위에 거랑 비슷한데 얘는 인자 안넣으면 부모 위젯 크기를 다 채워버린다.





실행결과를 보자.

tightFor(width : 100, height: 200)tightFor()expand()







간단하구만
오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글