- 普通的函数定义。在赋值之后,会丢失函数签名信息
class SortedCollection {
Function compare;
SortedCollection(int f(Object a, Object b)) {//比较麻烦,不美观
compare = f;
}
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = new SortedCollection(sort);
// All we know is that compare is a function,
// but what type of function?
assert(coll.compare is Function);// 丢失了函数的具体的信息,函数签名信息
}
复制代码
- 给函数起一个别名,使用比较方便。例如定义一个方法的回调,直接使用别名定义。
//这是flutter中使用最多的例子
typedef int Compare(Object a, Object b);
class SortedCollection {
Compare compare;
SortedCollection(this.compare);
}
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
void main() {
SortedCollection coll = new SortedCollection(sort);
assert(coll.compare is Function);
assert(coll.compare is Compare);
}
复制代码
- 高级用法,泛型函数别名
typedef int Compare<T>(T a, T b);
int sort(int a, int b) => a - b;
void main() {
assert(sort is Compare<int>); // True!// 判断函数的具体的类型
}
复制代码
- 实际案例
// https://docs.flutter.io/flutter/material/PopupMenuButton-class.html
new PopupMenuButton<WhyFarther>(
onSelected: (WhyFarther result) { setState(() { _selection = result; }); },
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[ // 这是构建菜单项的函数
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: const Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: const Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: const Text('Being a self-starter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: const Text('Placed in charge of trading charter'),
),
],
)
复制代码
- itemBuilder自定的类型PopupMenuItemBuilder
itemBuilder → PopupMenuItemBuilder<T> // itemBuilder 字段的类型
复制代码
- PopupMenuItemBuilder 函数具体的定义
List<PopupMenuEntry<T>> PopupMenuItemBuilder(
BuildContext context
)
复制代码
这个函数将被PopupMenuButton使用,创建PopupMenu的item。
-
参考
https://docs.flutter.io/flutter/material/PopupMenuButton-class.html 【PopupMenuButton】
https://www.dartlang.org/guides/language/language-tour#typedefs 【typedefs 用法】