【问题标题】:Dart Null Safety giving errors for typedef FunctionDart Null Safety 为 typedef 函数提供错误
【发布时间】:2021-08-30 12:59:20
【问题描述】:

我有一个例子,works in dart before null safety 不在upgrading to Null safety 之后。我不知道发生了什么。

它给了我错误 “动态函数()?”类型的值无法从方法“doSomething”返回,因为它的返回类型为“动态函数()”

但我没有将任何东西定义为 Nullable。

typedef RandomFunction = Function();

class RegisteredFunctions {
  Map<String, RandomFunction> types = {};

  static final RegisteredFunctions _registry = RegisteredFunctions._init();
  RegisteredFunctions._init() {}

  factory RegisteredFunctions() {
    return _registry;
  }

  void registerFunction(String name, RandomFunction func) {
    types[name] = func;
  }

  RandomFunction doSomething(String id) => types[id]; //<---- gives error
}

void doStuff(){
  print('Doing Something');
}

void main() {
  RegisteredFunctions functions = RegisteredFunctions();
  
  functions.registerFunction('func1', doStuff);
  functions.doSomething('func1')();
}

【问题讨论】:

  • 我想通了.. 使用后缀将地图转换为不可为空!修复。 (即:类型[id]!)

标签: dart


【解决方案1】:

对于其他试图弄清楚的人.. 这解决了它。

typedef RandomFunction = Object? Function();

class RegisteredFunctions {
  Map<String, RandomFunction> types = {};

  static final RegisteredFunctions _registry = RegisteredFunctions._init();
  RegisteredFunctions._init() {}

  factory RegisteredFunctions() {
    return _registry;
  }

  void registerFunction(String name, RandomFunction func) {
    types[name] = func;
  }

  // RandomFunction doSomething(String id) => types[id];  // <----- Doesn't work
  
  // RandomFunction doSomething(String id) => types[id]!; // <----- Works
  
  RandomFunction doSomething(String id) {                 // <----- Works better
    RandomFunction? func = types[id];
    
    if (func != null) {
      return func;
    } else {
      return (){};
    }    
  }
}

void doStuff(){
  print('Doing Something');
}

void doOtherStuff(){
  print('Doing Something else');
}

void main() {
  RegisteredFunctions functions = RegisteredFunctions();
  
  functions.registerFunction('func1', doStuff);
  functions.registerFunction('func2', doOtherStuff);
  
  functions.doSomething('func1')();
  functions.doSomething('func2')();
}

【讨论】:

  • Aaaaand... 您刚刚将一些可能的编辑时错误移到了运行时错误中。尽量不要那样做。使用 !几乎总是一种代码气味。
  • 另一件事:不要使用 Function()。拼写出来,比如 Object? Function() 如果它真的可以是一个返回不带参数的可空类型的函数。
  • 谢谢@Randal Schwartz。我用更简洁的解决方案更新了我的 DartPad 示例(上面链接)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
相关资源
最近更新 更多