dart函数式编程

flutter所用的dart语言是支持函数式编程的,也就是可以把函数当成一个变量,甚至作为一个参数传给其他的函数,下面是一些基本的用法:

1. 声明一个函数类型的变量

1
2
3
var action = () {
//TODO: 函数本体
};

2. 一个函数生成一个新函数并返回

1
2
3
4
5
jumpPage(context, nextPage) {
return () {
Navigator.of(context).push(CupertinoPageRoute(builder: (context){return nextPage;}));
};
}

3. 将一个函数作为参数传递给另一个函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MenuState extends State<Menu> {
final text;
final icon;
final action;
MenuState(this.text, this.icon, this.action);

@override
Widget build(BuildContext context) {
return CupertinoButton(
child: Text("按钮"),
onPressed: () {
action();
},
),
}
}