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),
);
})
);
}
}
'🐦 플러터' 카테고리의 다른 글
[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 |