flutter的switchpattern
abstract class RzBaseModel {
const RzBaseModel();
factory RzBaseModel.fromJson(Map<String, dynamic> json) {
return switch (json['type']) {
'user' => UserModel.fromJson(json),
'product' => ProductModel.fromJson(json),
'order' => OrderModel.fromJson(json),
String() => throw FormatException('Unknown type: ${json['type']}'),
_ => throw const FormatException('Missing type field in JSON'),
};
}
}
主要特点:
- 模式守卫 (Pattern Guards):使用 when 添加额外条件
解构模式:可以直接从对象或列表中提取值 - 通配符模式:使用 _ 匹配任意值
逻辑运算符:可以使用 &&、|| 组合多个模式
变量声明:可以在模式中声明变量
// API 响应处理
void handleApiResponse(Map<String, dynamic> response) {
switch (response) {
case {'status': 200, 'data': Map data}:
handleSuccessResponse(data);
case {'status': int code, 'error': String message} when code >= 400:
handleErrorResponse(code, message);
case {'status': int code} when code >= 500:
handleServerError(code);
default:
handleUnknownResponse(response);
}
}