对枚举使用 switch
本课属于 Coddy Flutter 学习旅程的“适配不同屏幕的布局”单元。第 19 课,共 30 课。
图库在手机上每行应显示 2 张照片,在平板电脑上每行应显示 4 张。你可以写 if 和 else,但当枚举的每个值都需要单独处理时,使用 switch 会更清晰:
int columns;
switch (type) {
case ScreenType.phone:
columns = 2;
case ScreenType.tablet:
columns = 4;
}Dart 会检查 type,并运行匹配的 case 下方的语句,而且只运行这些语句。然后,程序会继续运行右花括号之后的语句。
声明 columns 时,它还没有值。这是允许的,因为每个分支都会为它赋值。Dart 会检查枚举的每个值是否都有对应的分支:如果漏掉一个值,代码就无法编译,并会报错指出缺少的值。
挑战
简单网格始终有 2 列。在 return 前,声明 int columns;,并使用 switch 根据 type 设置它:手机上设为 2,平板上设为 4。然后将 columns 用作网格的 crossAxisCount。
亲手试试
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)),
),
],
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
适配不同屏幕的布局中的所有课
自己练习: Flutter 在线编译器