如何通过数字n调用Dart函数列表中的对应函数
按数字索引调用函数的优雅实现
你原来的Map写法问题在于,functionOne()是直接执行函数并存储其返回值(这里是void,实际存的是null),而不是存储函数本身的引用。要实现按数字调用函数并传参,最规范优雅的方式是用List存储函数引用(或修正Map的存储方式),以下是具体方案:
方案一:用List存储函数(推荐)
因为你的需求是按连续数字索引调用函数,List的天然索引特性比Map更直观,代码更简洁:
import 'dart:math'; // 定义目标函数 void functionOne(int x) => print("the randomly generated number is $x"); void functionTwo(int x) => print("the inverse of the randomly generated number is ${1/x}"); // 将函数引用存入List,索引对应数字n final List<void Function(int)> functionList = [functionOne, functionTwo]; void main() { final intValue = Random().nextInt(functionList.length); // 用length更灵活,新增函数无需修改此处 final biggerIntValue = Random().nextInt(100) + 1; // 通过索引调用函数并传入参数 functionList[intValue](biggerIntValue); }
如果需要类型更清晰,可以用typedef定义函数类型:
import 'dart:math'; // 定义函数类型别名,规范参数和返回值 typedef IntParamVoidFunc = void Function(int); void functionOne(int x) => print("the randomly generated number is $x"); void functionTwo(int x) => print("the inverse of the randomly generated number is ${1/x}"); final List<IntParamVoidFunc> functionList = [functionOne, functionTwo]; void main() { final intValue = Random().nextInt(functionList.length); final biggerIntValue = Random().nextInt(100) + 1; functionList[intValue](biggerIntValue); }
方案二:修正Map的写法
如果坚持用Map,只需去掉函数后的括号,存储函数本身而非执行结果:
import 'dart:math'; void functionOne(int x) => print("the randomly generated number is $x"); void functionTwo(int x) => print("the inverse of the randomly generated number is ${1/x}"); // 存储函数引用,而非执行函数 final Map<int, void Function(int)> example = {0: functionOne, 1: functionTwo}; void main() { final intValue = Random().nextInt(2); final biggerIntValue = Random().nextInt(100) + 1; // 调用时加入参数(注意用!断言非空,或先判断key是否存在) example[intValue]!(biggerIntValue); }
方案对比
- 相比多分支
if方案,List/Map的方式扩展性更强:新增函数只需在List/Map中添加条目,无需修改调用逻辑。 - List方案更适合连续数字索引的场景,代码更简洁直观;Map方案适合非连续或自定义数字键的场景。
内容的提问来源于stack exchange,提问作者crustification
相关产品推荐
相关产品推荐

