You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中if语句内case语法的用法解析及示例求助

Dart中if-case模式匹配语法解析

这是Dart 3.0新增的模式匹配特性,用if-case可以把「类型检查+空值校验+变量绑定」三个操作合并成一行,比传统写法更简洁直观。

你的代码语法拆解

原代码里的判断语句:

if (filter case TreeSearchResult<Node> filter?) {
  return node.children.where(filter.hasMatch);
}

等价于传统写法:

if (filter != null && filter is TreeSearchResult<Node>) {
  final nonNullFilter = filter as TreeSearchResult<Node>;
  return node.children.where(nonNullFilter.hasMatch);
}

这里的filter?是「可空模式」,作用是:

  1. 先检查filter是否为非空值
  2. 再校验它的类型是TreeSearchResult<Node>
  3. 匹配成功后,把这个非空的实例重新绑定到filter变量(此时filter是不可空的TreeSearchResult<Node>,可以直接调用它的方法)

基础示例快速理解

1. 可空字符串的非空匹配

String? username = "bob123";

if (username case String username?) {
  print("当前用户:$username"); // 这里username是不可空的String
}

2. 多类型分支判断

Object value = true;

if (value case bool isEnabled) {
  print("开关状态:$isEnabled");
} else if (value case double price) {
  print("商品价格:$price");
}

3. 复杂结构匹配(比如列表)

List<String>? fruits = ["苹果", "香蕉", "橙子"];

if (fruits case [String first, String second, String third]?) {
  print("前三种水果:$first、$second、$third");
}

内容的提问来源于stack exchange,提问作者Charin Nawaritloha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:42:47