1. Dart 参数

Dart 函数的参数分 3 种类型:

  • 位置参数
  • 命名参数
  • 可选位置参数

1.1 位置参数 (positional parameters)

参数位置重要,名称任意,

// 定义
void debugger(String message, int lineNum) {}// 调用
debugger('A bug!', 55);

参数不能多,不能少,实参与形参从左到右一一按位置对应,这是最基本的参数。

1.2 命名参数 (named Parameters)

命名参数:一般函数参数个数数量较多,比如有几十个,按位置传递参数的方法容易出错,不现实。此时可使用命名参数。对于命名参数,参数位置无关紧要,名称重要。
定义函数时,将参数放在花括号中,调用时,指定参数名称。

// 定义
void debugger({String message, int lineNum}) {}// 调用,位置无关紧要,
// 写成 debugger(lineNum: 44, message: 'A bug!'); 也可以
debugger(message: 'A bug!', lineNum: 44);

命名参数默认可选,如果需要指定要求参数必须提供,可使用 @required 或者 required,具体用哪一个,与 Dart 版本相关。

如果使用 Dart 1.12 及以后的版本,下面的函数,因为变量默认为 sound null safety(可靠的空安全),函数

void debugger({String message}) {}

要么改成

void debugger({required String message}) {}

要么改成

void debugger({String? message}) {}

1.3 可选位置参数 (optional positional parameters)

放在中括号中的参数是可选位置参数,例如,以下代码中的参数 z

int addSomeNums(int x, int y, [int z]) {int sum = x + y;if (z != null) {sum += z;}return sum;
}addSomeNums(5, 4); // okay, because the third parameter z is optional
addSomeNums(5, 4, 3); // also okay

可选位置参数可以指定默认值:

// function signature
int addSomeNums(int x, int y, [int z = 5]) => x + y + z;// calling that function without passing in the third argument
int sum = addSomeNums(5, 6);
assert(sum == 16); // 5 + 6 + 5// calling that function with passing in the third argument
int sum2 = addSomeNums(5, 6, 10);
assert(sum2 == 21); // 5 + 6 + 10

方括号 [ ] 中的所有参数全部可选, 也就是说,它们必须为 nullable,对于 Dart 1.12 及以后的版本,可以在参数类型后加?,允许其值为 nullDart 1.11 及之前的版本不需要加。

void optionalThreeGreeting(int numberOfTimes,[String? name1, String? name2, String? name3]) {}

1.4 参数组合形式

  • 位置参数
  • 命名参数
  • 可选位置参数
  • 位置参数 + 命名参数
// ✅
String greeting(String name, {String? message}) { ... }
  • 位置参数 + 可选位置参数
// ✅
void hide(bool hidden, [bool? animated]) { ... }

不能混合命名参数与可选位置参数:

// ❌
int mixedSum({required int a, int? b}, [int? c]) { ... }

2. @requiredrequired 的区别


As of Dart 2.12, the required keyword replaces the @required meta annotation. For detailed info look into the official FAQ. The following answer has been updated to reflect both this and null safety.

@required is just an annotation that allows analyzers let you know that you’re missing a named parameter and that’s it. so you can still compile the application and possibly get an exception if this named param was not passed.
However sound null-safety was added to dart, and required is now a keyword that needs to be passed to a named parameter so that it doesn’t let the compiler run if this parameter has not been passed. It makes your code more strict and safe.
If you truly think this variable can be null then you would change the type by adding a ? after it so that the required keyword is not needed, or you can add a default value to the parameter.


Dart 1.12 版开始,使用关键字 required 取代 @required 标记 (同时预设开启sound null safety, 没有特别说明的type 都是 non-nullable 的。)

void debugger({String message, int lineNum}) {}

命名参数默认可选,但是如果要求调用此函数时必须提供哪些参数,对于 Dart 1.12 之前的版本,使用 @required annotation,对于 Dart 1.12 以及之后的版本,使用 required keyword

以下是一个 Flutter project, 设置 pubspec.yaml 中的 Dart 版本:

environment:sdk: ">=2.11.0 <3.0.0"

测试函数 func

class _MyHomePageState extends State<MyHomePage> {// function for testvoid func({@required String arg1, @required int arg2}) {print(arg1);print(arg2);}@overrideWidget build(BuildContext context) {// Ok,compile pass// 使用 @required 标记, 分析器会指出命名参数丢失,// 但对实际编译运行没有影响。func(); return Scaffold(appBar: AppBar(title: const Text("title"),),body: const Center(child: Text('body')),);}
}

如果改为使用 Dart 2.12,同时 @required 改为 required,此时如果丢失参数,将无法通过编译。

所以,required 作为关键字强制要求提供参数@required 只是一种标记required 强于 @required

environment:sdk: ">=2.17.6 <3.0.0"
class _MyHomePageState extends State<MyHomePage> {void func({required String arg1, required int arg2}) {print(arg1);print(arg2);}@overrideWidget build(BuildContext context) {// 无法通过编译 !!!// Error: Required named parameter 'arg1' must be provided.func();return Scaffold(appBar: AppBar(title: const Text("title"),),body: const Center(child: Text('body')),);}
}

  1. https://flutterbyexample.com/lesson/function-arguments-default-optional-named
  2. https://ithelp.ithome.com.tw/articles/10271892?sc=hot
  3. https://stackoverflow.com/questions/54181838/flutter-required-keyword
  4. https://stackoverflow.com/questions/67642000/what-is-the-difference-between-required-and-required-in-flutter-what-is-the-di
  5. https://stackoverflow.com/questions/64621051/how-to-enable-null-safety-in-flutter
  6. https://sarunw.com/posts/dart-parameters/#how-to-declare-parameters-in-dart

Flutter: Dart 参数,以及 @required 与 required相关推荐

  1. 用Flutter + Dart快速构建一款绝美移动App

    作者 | Wojciech Kuroczycki 译者 | 弯月 来源 | CSDN(ID:CSDNnews) 如今,与前端或移动相关的新框架层出不穷.所有从事Web开发的人都应该熟悉各种目不暇接的新 ...

  2. 不用掉一根头发!用 Flutter + Dart 快速构建一款绝美移动 App

    作者 | Wojciech Kuroczycki 译者 | 弯月 出品 | CSDN(ID:CSDNnews) 如今这个时代,与前端或移动相关的新框架层出不穷.所有从事Web开发的人都应该熟悉各种目不 ...

  3. Flutter 动态化 | Flutter + Dart 三端一体化动态化平台实践

    导读 FairPushy 是基于Flutter+Dart三端一体化打造的动态更新平台主要由Web + Server + Native全部使用Flutter+Dart编写,为Flutter动态化场景提供 ...

  4. 【Flutter】Flutter 开发环境搭建 ( Android Studio 下 Flutter / Dart 插件安装 | Flutter SDK 安装 | 环境变量配置 | 开发环境检查 )

    文章目录 一.Flutter 学习资料 二.Flutter 开发环境搭建 三.Android Studio 环境安装 Flutter / Dart 插件 四.下载 Flutter SDK 五.设置 F ...

  5. Flutter Dart:用数字分组显示大数字

    Flutter & Dart:用数字分组显示大数字 大家好,我是坚果,我的公众号"坚果前端", 用逗号显示大数字作为千位分隔符将增加可读性.这篇简短的文章将向您展示如何借助 ...

  6. flutter offset_Flutter 仿微信界面聊天室 | 基于 (Flutter+Dart) 聊天实例

    1.项目介绍 Flutter是目前比较流行的跨平台开发技术,凭借其出色的性能获得很多前端技术爱好者的关注,比如阿里闲鱼,美团,腾讯等大公司都在投入相关案例生产使用.flutter_chatroom项目 ...

  7. Flutter Dart SDK

    Flutter Dart SDK 在 Flutter SDK 中是包含了 Dart SDK的. 一般 Dart 的sdk 的路径为 your_flutter_dir/bin/cache/dart-sd ...

  8. flutter图片聊天泡泡_基于 Flutter+Dart 聊天实例 | Flutter 仿微信界面聊天室

    1.项目介绍 Flutter是目前比较流行的跨平台开发技术,凭借其出色的性能获得很多前端技术爱好者的关注,比如阿里闲鱼,美团,腾讯等大公司都有投入相关案例生产使用. flutter_chatroom项 ...

  9. flutter dart ..addAll

    List<dynamic> test1=[];List<dynamic> test2=[];List<dynamic> test3=[];List<dynam ...

  10. flutter dart空安全

    空安全版本 空安全(Sound null safety)是 Dart 2.12 中新增的一项特性,空安全特性并不是 Dart 独有的, 健全的空安全已在 Dart 2.12 和 Flutter 2 中 ...

最新文章

  1. 二代数据 模拟软件wgsim
  2. Jquery中获取表单的值并提交
  3. 服务器连接异常系统无法登录,win10系统无法登录LOL提示“服务器连接异常”的解决方法...
  4. JAVA基础--final、static区别以及类加载顺序
  5. 用友2020校招java笔试题_用友Java类笔试题大全
  6. fasttext 文本分类_4种常见的NLP实践思路【特征提取+分类模型】
  7. C++离航篇——引用,const
  8. JavaWeb 项目时 启动一个线程
  9. PAT (Basic Level) Practice1010 一元多项式求导
  10. erp的术语-jde系统
  11. 手把手教你制作一个操作系统
  12. 真3D麻将游戏桌面适配任意分辨率
  13. win10 python ffmpeg推流到b站
  14. 正负数据如何归一化_归一化方法的区别
  15. WPS2000系列之四图文混编(转)
  16. 全民居家都带不动的AI健身,到底是不是伪命题?
  17. 北大青鸟 当当网网 js 上机作业
  18. Dicom标签之(0020,0037) Image Orientation (Patient)
  19. 青春无敌?那只是一瞬间
  20. 【Spring】Spring入门

热门文章

  1. 记GMGDC2013大会
  2. javascript中function前面的符号的意思!
  3. android 连接蓝牙耳机 的判断代码,如何验证Android上是否连接了蓝牙耳机?
  4. 树莓派笔记17: 语音机器人
  5. 【杀毒】-记一次挖矿病毒sysdrr杀毒
  6. unity功能开发——实名认证
  7. 只需3天即可启动应用发布营销核对清单
  8. RAR压缩包密码如何解密
  9. 计算机语言栏怎么打开,电脑语言栏不见了怎么解决 电脑语言栏找回方法【图文】...
  10. Oracle中动态SQL详解(EXECUTE IMMEDIATE)