Flutter函数

在Dart中,函数为 一等公民,可以作为参数对象传递,也可以作为返回值返回。

函数定义

Dart 复制代码
// 返回值 (可以不写返回值,但建议写)、函数名、参数列表
showMessage(String message) {
  //函数体
  print(message);
}

void showMessage(String message) {
  print(message);
}

可选参数

位置参数:用方括号[]表示,参数根据位置传递给函数;

Dart 复制代码
void showNewMessage(int age, [String? birthday]) {
  if (birthday != null && birthday.isNotEmpty) {
    print("birthday$birthday");
  } else {
    print("age$age");
  }
}

命名参数:用大括号表示,参数根据名称传递给函数;

Dart 复制代码
// {}命名参数,required 表示该参数是必须的
void showFirstMessage({required String content, int? time}) {
}

  

上面?(问号)修饰符 是 nullable修饰符,用于修饰参数,表示此参数可传,可不传。

? 操作符:可选参数,如果不为null则执行

Dart 复制代码
//? 操作符:可选参数,如果不为null则执行
String? content;
int size = content?.length ?? 0;

//?? 操作符:表示如果表达式为空值时,提供一个默认值

Dart 复制代码
int size = content?.length ?? 0;

如下面Container的构造函数使用了命名参数

Dart 复制代码
  Container({
    super.key,
    this.alignment,
    this.padding,
    this.color,
    this.decoration,
    this.foregroundDecoration,
    double? width,
    double? height,
    BoxConstraints? constraints,
    this.margin,
    this.transform,
    this.transformAlignment,
    this.child,
    this.clipBehavior = Clip.none,
  })

@required : 对命名可选参数添加required关键字,让对应的命名可选参数变成必传参数

Dart 复制代码
MaterialPageRoute({
    required this.builder,
    super.settings,
    this.maintainState = true,
    super.fullscreenDialog,
    super.allowSnapshotting = true,
    super.barrierDismissible = false,
  })

箭头/匿名函数

箭头函数用于定义单行函数,用 箭头符号(=>) 分隔参数和函数体,并省略了函数体的大括号:

Dart 复制代码
int sum(int a, int b) => a + b;

函数作为参数

Dart 复制代码
String append(String title, String content) => "$title&$content";

void testFunction(String title, String content, Function append) {
  String result = append(title, title);
  print(result);
}

函数作为返回值

Dart 复制代码
int sum(int a, int b) => a + b;

Function testReturnFunction() {
  return sum;
}
相关推荐
景天科技苑1 天前
【Go】Go语言中延迟函数、函数数据的类型、匿名函数、闭包等高阶函数用法与应用实战
后端·golang·回调函数·defer·匿名函数·闭包·go函数数据类型
qq_172805597 天前
GO 匿名函数
go·匿名函数
Trouvaille ~19 天前
【Python篇】Python 函数综合指南——从基础到高阶
开发语言·python·生成器·异步函数·高阶函数·匿名函数·闭包
ygluu23 天前
游戏服务器架构:基于匿名函数的高性能异步定时器系统
匿名函数·游戏服务器架构·高性能定时器·异步定时器
埜玊2 个月前
Python函数 之 匿名函数
python·匿名函数
韩曙亮4 个月前
【OpenHarmony】TypeScript 语法 ④ ( 函数 | TypeScript 具名函数和匿名函数 | 可选参数 | 剩余参数 | 箭头参数 )
前端·javascript·typescript·harmonyos·openharmony·可选参数·剩余参数
zengk5628 个月前
四、Kotlin 表达式
匿名函数·kotlin 常量和变量·if-else 表达式·when 表达式·运算符重载函数·lambda 表达式·中缀表达式
微小冷10 个月前
Julia函数进阶:匿名函数、函数复合、管道计算
julia·管道·函数式·匿名函数·函数复合·多参数
talk_81 年前
Jetpack:009-kotlin中的lambda、匿名函数和闭包
android·kotlin·lambda·匿名函数·闭包