[Flutter] LayoutBuilder 위젯 알아보기

2023. 6. 20. 10:48·🐦 플러터

LayoutBuilder

상위 위젯의 크기에 따라 달라질 수 있는 위젯 트리를 작성합니다.

프레임 워크가 레이아웃 시간에 작성기 함수를 호출하고 상위 위젯의 제약 조건을 제공한다는 점을 제외하면 작성기 위젯과 유사합니다. 이것은 부모가 자녀의 크기를 제한하고 자녀의 본질적인 크기에 의존하지 않을 때 유용합니다. 레이아웃 작성기의 최종 크기는 하위 크기와 일치합니다.

 

Builder 함수는 다음과 같은 경우에 호출됩니다:

  • 위젯을 처음으로 배치할 때
  • 상위 위젯이 다른 레이아웃 제약 조건을 통과하는 경우
  • 상위 위젯이 이 위젯을 업데이트하는 경우
  • builder 함수가 subscribes to change dependency

부모가 동일한 제약 조건을 반복적으로 통과하는 경우 레이아웃 중에 builder 함수가 호출되지 않습니다.

 

아래는 LayoutBuilder와 OrientationBuilder를 사용하는 예시입니다.

import 'package:flutter/material.dart';

enum ScreenSize {small, normal, large, extraLarge}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: PracticeLayoutBuilder(),
    );
  }
}

class PracticeLayoutBuilder extends StatefulWidget {
  const PracticeLayoutBuilder({Key? key}) : super(key: key);

  @override
  State<PracticeLayoutBuilder> createState() => _PracticeLayoutBuilderState();
}

class _PracticeLayoutBuilderState extends State<PracticeLayoutBuilder> {

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    // Check width of device
    print(width);

    return Scaffold(

      // Set OrientationBuilder as body
	     body: OrientationBuilder(

	 		// Set GridView.count as return of builder function
          	builder: (BuildContext context, Orientation orientation) {
            return GridView.count(

				// Set GridView.count's crossAxisCount depending on whether orientation is portrait
        	    crossAxisCount: orientation==Orientation.portrait ? 2:3,

				// Set 6 box() as children
 	     	    children: List.generate(6, (index) => box()),
            );
          },
        )
    );
  }

  Widget box(){
    return Container(
        margin: EdgeInsets.all(10),
        color: Colors.lightGreen,
        alignment: Alignment.center,

        // Set LayoutBuilder as child
				child: LayoutBuilder(

		    // Set Text('${constraints.maxWidth}') as return of builder function        
            builder: (BuildContext context, BoxConstraints constraints) {
              return Text('${constraints.maxWidth}',
				
				// Set color of the Text depending on whether constraints.maxWidth is greater than 160
                style: TextStyle(color: constraints.maxWidth>160 ? Colors.red : Colors.white),
              );
            })
    );
  }
}

Code Result

 

저작자표시 비영리 동일조건 (새창열림)

'🐦 플러터' 카테고리의 다른 글

[Flutter] Responsive User Interface를 구현해보자  (0) 2023.06.21
[Flutter] flutter_screenutil 패키지 알아보기  (0) 2023.06.20
[Xcode] Target debug_os_bundle_flutter_assets failed: ShaderCompilerException  (0) 2023.04.01
[Xcode] note: Building targets in dependency order  (0) 2023.04.01
[iOS] 플러터 IOS 시뮬레이터에서 Google 간편 로그인 안될 때  (0) 2023.01.05
'🐦 플러터' 카테고리의 다른 글
  • [Flutter] Responsive User Interface를 구현해보자
  • [Flutter] flutter_screenutil 패키지 알아보기
  • [Xcode] Target debug_os_bundle_flutter_assets failed: ShaderCompilerException
  • [Xcode] note: Building targets in dependency order
기멘기
기멘기
Handong Global University | Apple Developer Academy @ POSTECH
  • 기멘기
    현기의 비공식문서 🍎
    기멘기
  • 전체
    오늘
    어제

  • 링크

    • Github
    • Instagram

    • 전체 글 (79) N
      • 🍎 iOS (6)
        • 애플 디벨로퍼 아카데미 (6)
      • 🐦 플러터 (32)
      • 🤔 컴공 지식 (10)
        • 알고리즘 (3)
        • 네트워크 (7)
      • 🔥 문해력 상승 (8)
        • 백 준 (8)
        • 프로 그래머 스 (0)
      • 💬 이모저모 (12)
        • CRA 방학 프로젝트 (4)
        • 캡스톤 산학 프로젝트 (5)
        • PARD IT 협업 동아리 (2)
      • 💡 인사이트 (0)
        • 전공 관련 (0)
        • 기타 (0)
      • ✏️ 하루 회고 (TIL) (4) N
      • 🔍 ETC (7)
        • HTML-CSS-JS (4)

  • 인기 글


  • 최근 댓글


  • 최근 글


  • 블로그 메뉴

    • 티스토리 홈
    • 블로그 관리
    • 글 작성하기

  • hELLO· Designed By정상우.v4.10.3
기멘기
[Flutter] LayoutBuilder 위젯 알아보기
상단으로

티스토리툴바