如何在Dart中测试函数的存在?

Geo*_*zos 7 dart dart-mirrors

有没有办法在Dart中测试函数或方法的存在而不试图调用它并捕获NoSuchMethodError错误?我正在寻找类似的东西

if (exists("func_name")){...}
Run Code Online (Sandbox Code Playgroud)

测试名为的函数是否func_name存在.提前致谢!

Ale*_*uin 6

您可以使用镜像API执行此操作:

import 'dart:mirrors';

class Test {
  method1() => "hello";
}

main() {
  print(existsFunction("main")); // true
  print(existsFunction("main1")); // false
  print(existsMethodOnObject(new Test(), "method1")); // true
  print(existsMethodOnObject(new Test(), "method2")); // false
}

bool existsFunction(String functionName) => currentMirrorSystem().isolate
    .rootLibrary.functions.containsKey(functionName);

bool existsMethodOnObject(Object o, String method) => reflect(o).type.methods
    .containsKey(method);
Run Code Online (Sandbox Code Playgroud)

existsFunction仅测试functionName当前库中是否存在函数.因此,通过import语句可用的函数existsFunction将返回false.