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?是「可空模式」,作用是:
- 先检查
filter是否为非空值 - 再校验它的类型是
TreeSearchResult<Node> - 匹配成功后,把这个非空的实例重新绑定到
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
相关产品推荐
相关产品推荐

