欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Flutter函数

Flutter函数

2024/10/25 2:29:41 来源:https://blog.csdn.net/zhangying1994/article/details/142050029  浏览:    关键词:Flutter函数

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

函数定义

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

可选参数

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

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

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

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

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

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

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

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

int size = content?.length ?? 0;

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

  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关键字,让对应的命名可选参数变成必传参数

MaterialPageRoute({required this.builder,super.settings,this.maintainState = true,super.fullscreenDialog,super.allowSnapshotting = true,super.barrierDismissible = false,})

箭头/匿名函数

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

int sum(int a, int b) => a + b;

函数作为参数

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

 

函数作为返回值

int sum(int a, int b) => a + b;Function testReturnFunction() {return sum;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com