IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Flutter: Dart 参数,以及 @required 与 required -> 正文阅读

[移动开发]Flutter: Dart 参数,以及 @required 与 required

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 test
  void func({ String arg1,  int arg2}) {
    print(arg1);
    print(arg2);
  }

  
  Widget 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);
  }

  
  Widget 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
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-09-30 01:04:20  更:2022-09-30 01:07:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/20 3:26:11-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码