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

Dart语言中向函数传递参数时如何使用switch语句?

Dart分支判断的常见用法

普通switch语句

在Dart中,开发者可以使用switch语句替代冗长的if-then-else判断。

var command = 'OPEN';
switch (command) {
  case 'CLOSED':
    executeClosed();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
}

表达式场景下的分支判断

但部分场景下我们需要基于条件直接返回对应值,例如在函数调用、类实例化、变量赋值等场景中直接传入计算值。
我们期望的写法往往如下,但这种写法目前无法正常运行:

// 写法不生效,仅作需求示例
MakeNametag(
   adjustFontSize: switch(status) {
     case 'young' : return 'large';
     case 'old' : return 'largest';
     default: return 'normal';
    } //end switch
  }
);

如果仅存在两种判断分支,可使用条件运算符(有时也被称为三元运算符)实现需求:

// 可正常运行的实现方式
MakeNametag(
  adjustFontSize: ['old','young'].contains(status) ? 'larger' : 'normal');

JavaScript中也存在相同的运算符和同类问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:36:03