Flutter를 사용하다 보면 Expanded 위젯을 자주 접하게 됩니다. 이 글에서는 Expanded 위젯이 무엇인지, 왜 필요한지, 그리고 어떻게 사용하는지에 대해 쉽게 설명해드리겠습니다.
Expanded 위젯은 Row, Column, 또는 Flex 위젯 내에서 사용되어 남은 공간을 자식 위젯에게 할당합니다. 쉽게 말해, 화면에서 남은 공간을 특정 위젯이 차지하게 만드는 역할을 합니다.
Flutter의 레이아웃 시스템에서, Row와 Column 같은 위젯은 기본적으로 자식 위젯들을 가능한 공간 내에서 모두 표시하려고 합니다. 그런데 가끔은 특정 위젯이 남은 모든 공간을 차지하게 하고 싶을 때가 있습니다. 이때 Expanded 위젯을 사용합니다.
예를 들어, 가로 스크롤이 가능한 SingleChildScrollView를 Row 내에서 사용하려면 Expanded로 감싸줘야 스크롤이 올바르게 작동합니다. 그렇지 않으면 오버플로우 문제가 발생할 수 있습니다.
남은 공간을 채워야 할 때: 화면의 남은 공간을 특정 위젯이 차지해야 할 때 사용합니다.
동적으로 크기를 조정해야 할 때: 레이아웃 내에서 위젯의 크기를 동적으로 조정할 필요가 있을 때 사용합니다.
스크롤 가능한 영역을 만들 때: SingleChildScrollView와 함께 사용하여 스크롤 가능한 영역을 올바르게 만들고자 할 때 사용합니다.
다음은 Expanded 위젯을 사용하여 SingleChildScrollView가 올바르게 작동하도록 하는 예제 코드입니다:
class CalendarScreen extends StatelessWidget {
const CalendarScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).colorScheme.surface,
body: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30,
vertical: 70,
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 82,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Theme.of(context).colorScheme.secondary,
),
child: Row(
children: [
Container(
// width: 58,
padding: const EdgeInsets.symmetric(
horizontal: 20,
),
height: 58,
decoration: const BoxDecoration(
border: Border(
right: BorderSide(
color: Colors.black,
),
),
),
child: const Row(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("금"),
Text("08.02"),
],
),
],
),
),
const Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 20,
),
child: Row(
children: [
StaffProfileWidget(
imageName: "Ellipse 2.png",
),
StaffProfileWidget(
imageName: "Ellipse 3.png",
),
StaffProfileWidget(
imageName: "Ellipse 4.png",
),
StaffProfileWidget(
imageName: "Ellipse 5.png",
),
StaffProfileWidget(
imageName: "Ellipse 2.png",
),
StaffProfileWidget(
imageName: "Ellipse 3.png",
),
StaffProfileWidget(
imageName: "Ellipse 4.png",
),
],
),
),
),
)
],
),
),
],
),
),
),
);
}
}
Expanded는 부모 Row, Column, 또는 Flex 위젯 내에서 사용되며, 자식 위젯이 남은 공간을 모두 차지하게 합니다.
SingleChildScrollView와 함께 사용하여 올바르게 스크롤 가능한 영역을 만들 수 있습니다.
레이아웃 내에서 공간을 유연하게 관리하고자 할 때 Expanded를 사용합니다.
Expanded 위젯을 적절히 사용하면 Flutter 앱의 레이아웃을 더 유연하고 직관적으로 만들 수 있습니다.