switch 표현식
Coddy Flutter 여정의 화면 크기에 맞는 레이아웃 섹션에 포함된 레슨. 30개 중 20번째.
값만 선택하는 switch는 switch 표현식으로 더 짧게 작성할 수 있습니다. 이 표현식은 직접 저장할 수 있는 값을 반환합니다.
final columns = switch (type) {
ScreenType.phone => 2,
ScreenType.tablet => 4,
};각 줄은 열거형의 값, 화살표 =>, 그리고 해당 값에 대한 결과로 구성되며, 쉼표로 끝납니다. case도 할당도 없으며, 전체 switch는 하나의 문장이므로 ;로 끝납니다.
switch 표현식에는 모든 값에 대한 결과가 있어야 합니다. 열거형에 값을 추가하면, 해당 값에 대한 줄이 없는 그 열거형을 대상으로 하는 모든 switch는 컴파일되지 않고, 누락된 case를 가리키는 오류가 발생합니다. Dart는 업데이트가 필요한 각 위치를 보여 줍니다.
챌린지
중급갤러리에 데스크톱 레이아웃을 추가하세요:
enum ScreenType에desktop을 추가하세요- 너비가
1000이상일 때type을ScreenType.desktop으로 설정하세요 switch문을 2개, 4개, 6개의 열을 반환하는 switch 표현식으로 바꾸세요
직접 해보기
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
enum ScreenType { phone, tablet }
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
var type = ScreenType.phone;
if (width >= 600) {
type = ScreenType.tablet;
}
int columns;
switch (type) {
case ScreenType.phone:
columns = 2;
case ScreenType.tablet:
columns = 4;
}
final photos = ['Beach', 'Forest', 'City', 'Desert', 'Lake', 'Snow', 'Island', 'Canyon'];
return Scaffold(
appBar: AppBar(title: Text('Gallery: ${type.name}')),
body: GridView.count(
crossAxisCount: columns,
children: [
for (final photo in photos)
Container(
margin: const EdgeInsets.all(4),
color: Colors.cyan.shade100,
child: Center(child: Text(photo)),
),
],
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
화면 크기에 맞는 레이아웃의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러