Flutter dart 函数总结
// 此处需要配置pubspec.yaml
// pub get
import 'package:meta/meta.dart';
/**
* dart 函数
* typedef
* Function
*/
// typedef 定义函数别名 类似c++ 函数指针的定义
// typedef 可以单独的设置别名 和返回值 参数
// typedef 也可以配合 Function 声明
// Function 是类型
typedef SayHelloFun(int i, int j);
typedef DoSth(var str);
typedef HelloworldFun = Function(String str);
typedef HelloworldFun2 = String Function(String str);
typedef String HelloworldFun3(String str);
void main(){
print('dart 函数');
SayHelloFun sayHello = sayHello1;
sayHello(1, 2);
HelloworldFun helloworldFun = helloworld;
helloworldFun("helloworld");
HelloworldFun2 helloworldFun2 = helloworld2;
helloworldFun2('helloworld2');
HelloworldFun3 helloworldFun3 = helloworld2;
helloworldFun3('helloworld3');
// 函数作为形参
todo(()=>print('函数作为参数'));
todo2(()=>print('函数作为参数2'));
todo3(helloworld, '使用Function作为参数,且传入该函数需要的形参2');
todo4(helloworld, '直接声明带参数的函数 作为形参1, 且传入该函数需要的形参2');
todo5(helloworld, '使用typedef 命名的函数作为形参1,且传输该函数需要的形参2');
// 词法闭包
Function addFun = makeAdd(100);
print(addFun(1));
print(addFun(2));
var addFun2 = makeAdd2(1000);
print(addFun2(1));
AddFun addFun3 = makeAdd2(10000);
print(addFun3(1));
// 函数作为容器成员
List<AddFun> funList = <AddFun>[addFun3];
// 遍历函数容器 foreach的形参为 以该容器的成员类型 为形参的任意函数
funList.forEach((AddFun fun)=>print(fun(1)));
}
void helloworld(String str) {
print(str);
}
String helloworld2(String str){
print(str);
}
// 函数体只有一个表达式 可以使用=>
void helloworld4(String str) => print(str);
String helloworld5() => '';
// 函数作为参数
void todo(void doFun()) {
doFun();
}
void todo2(Function fun){
fun();
}
// Function 为类型 fun为任意函数的实例
void todo3(Function fun, String str){
fun(str);
}
// 直接声明函数 作为形参
void todo4(void funParam(String str) , String str) {
funParam(str);
}
// typedef 命名的函数作为形参
void todo5(HelloworldFun fun, String str){
fun(str);
}
dynamic sayHello1(int i, int j) {
print('helloworld' + i.toString() + ' ' + j.toString());
}
//Function 函数作为返回值, 闭包,i为形参但始终有效
Function makeAdd(int i) {
return (int j)=> i + j;
}
//typedef 命名的函数为返回值,闭包, i始终有效
typedef int AddFun(int j);
AddFun makeAdd2(int i) {
return (int j)=> i + j;
}
// 暂时没有测试了
class Student{
// 函数作为成员变量
DoSth actionFun;
var name;
String address;
Student({
@required this.actionFun,
this.name,
this.address,
});
void sayHello(){
print('Student sayHello');
}
}