Switch on an Enum
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 19 of 30.
A gallery should show 2 photos in a row on a phone and 4 on a tablet. You could write if and else, but when each value of an enum needs its own answer, a switch reads better:
int columns;
switch (type) {
case ScreenType.phone:
columns = 2;
case ScreenType.tablet:
columns = 4;
}Dart looks at type and runs the lines under the case that matches, and only those. Then it carries on after the closing brace.
columns has no value when it is declared. That is allowed because every case gives it one. Dart checks that every value of the enum has a case: leave one out and the code does not compile, with an error naming the missing value.
Challenge
EasyThe grid always has 2 columns. Before the return, declare int columns; and set it with a switch on type: 2 on a phone, 4 on a tablet. Then use columns as the grid's crossAxisCount.
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;
}
final photos = ['Beach', 'Forest', 'City', 'Desert', 'Lake', 'Snow', 'Island', 'Canyon'];
return Scaffold(
appBar: AppBar(title: Text('Gallery: ${type.name}')),
body: GridView.count(
crossAxisCount: 2,
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