Switch Expressions
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 20 of 30.
A switch that only picks a value can be written shorter, as a switch expression. It gives back a value you store directly:
final columns = switch (type) {
ScreenType.phone => 2,
ScreenType.tablet => 4,
};Each line is a value of the enum, an arrow =>, and the result for it, ending with a comma. There is no case and no assignment, and the whole switch ends with ; because it is one statement.
A switch expression must have an answer for every value. Add a value to the enum, and every switch on it that has no line for it stops compiling, with an error pointing at the missing case. Dart shows you each place that needs updating.
Challenge
MediumAdd a desktop layout to the gallery:
- add
desktoptoenum ScreenType - set
typetoScreenType.desktopwhen the width is1000or more - replace the
switchstatement with a switch expression that gives 2, 4 and 6 columns
Try it yourself
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)),
),
],
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Layout That Fits
1Sharing a Row
Expanded Fills the RowSharing Space With flexFlexible Hugs Its ChildSpacer Pushes ApartPractice on your own: Online Flutter compiler