1. 상하로 배치
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Widget을 상하로 배치'),
),
body: Body(),
),
));
}
class Body extends StatelessWidget {
const Body({super.key});
@override
Widget build(BuildContext context) {
return Container(
height: 300,
width: double.infinity,
color: Colors.black12,
child: Column(
mainAxisAlignment: MainAxisAlignment.center, //상하좌우로 중앙
crossAxisAlignment: CrossAxisAlignment.start, //좌우폭 조정 start = 왼쪽끝, end = 오른쪽 끝
children: [
Container(
color: Colors.blue,
width: 100,
height: 80,
child: Text('Container1'),
),
Container(
color: Colors.grey,
width: 100,
height: 80,
child: Text('Container2'),
),
Container(
color: Colors.orange,
width: 100,
height: 80,
child: Text('Container3'),
),
],
),
);
}
}
이와 같은 화면을 만든 코드이다.
stless로 Body를 만들었고,
Body 내에서 Container를 하나 만든다음
그 안에 3개의 Container를 넣어두었다.
그리고 이 3개의 Container를
상하좌우로 중앙으로 배치인 mainAxisSize를 사용한 후에
좌우폭을 조정하는 crossAxisAlignment를 사용하여
상하로는 중앙, 좌우로는 외쪽 시작점에 붙게 배치한 모습이다.
2. 좌우로 배치
위의 child : Column을 child : Row 로 수정하면 좌우로 배치가 가능하다.
# 추가내용
화면의 크기보다 내용이 더 많을 경우 스크롤을 이용할 수 있다.
Column을 쌓기 전에 SingleChildScrollView를 추가한다.
Row 의 경우에는 scrollDirection : Axis.horizontal 이라는 옵션을 추가해야 한다.
# 위젯 사이즈 비율로 설정
class Body extends StatelessWidget {
const Body({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
Flexible(flex: 1 ,child: Container(color: Colors.blue)),
Flexible(flex: 2,child: Container(color: Colors.orange)), //1:2비율로 배치함
],
);
}
}
Flexible을 통해서 비율로 배치를 할 수도 있다.
Expanded 객체도 있는데, Flexible과 사용법은 같고,
사이즈가 줄어들지 않으며 남은 공간을 채울 때 사용할 수 있다.
Row 로도 똑같이 적용이 가능하다.
3. 위젯 겹겹이 쌓아 배치
class Body extends StatelessWidget {
const Body({super.key});
@override
Widget build(BuildContext context) {
return Stack(
children: [
Container(
width: 400,
height: 400,
color: Colors.black,
),
Container(
width: 300,
height: 300,
color: Colors.blue,
),
Container(
width: 200,
height: 200,
color: Colors.grey,
),
Positioned(
bottom: 50,
right: 30,
child: Container( //뒤에 쓸 수록 앞쪽으로 배치
width: 100,
height: 100,
color: Colors.green,
),
),
],
);
}
}
다음과 같이 Stack을 이용하여 겹쳐서 쌓아 올릴 수 있다.
특히 Positioned를 통해서 위치를 세밀하게 조정할 수도 있다.
Align(
alignment: Alignment.topRight,
child: Container(
width: 100,
height: 100,
color: Colors.green,
),
),
이와같이 positioned 대신 Align을 사용할 수도 있는데,
Alignment에 가운데, 좌상단, 우상단 같은 옵션을 통해서 편하게 배치할 수도 있고, xy좌표를 사용하는 것도 가능하다.
'Development > Flutter Development' 카테고리의 다른 글
Flutter의 입력 (feat. stful) (0) | 2024.03.01 |
---|---|
Flutter의 State (0) | 2024.02.21 |
Flutter 위젯 (0) | 2024.02.09 |
Flutter 기초 (~ing) (0) | 2024.02.09 |