首页 > 解决方案 > 带有泛型的 Dart 高阶函数

问题描述

我正在尝试创建一个简单的调试/打印函数,我可以在处理 Dart 中的 Future 结果时通过一系列then管道。

我的函数定义如下:

import 'dart:async';

typedef FutureOr<T> Pipe<T>(T pipeThrough);
Pipe<A> debug<A>(String log) {
  return (A pipeThrough) {
    print(log);
    return pipeThrough;
  };
}

它将返回一个函数,该函数仅通过从 Future 链接收到的任何内容进行管道传输,并且在此之前它将打印已发送到debug的消息日志

我使用该功能的方式非常简单:

Future<Map> load(String folder) {
  return File(Paths.of([folder, 'data.json']))
      .readAsString()
      .then((s) => jsonDecode(s))
      .then(debug<Map>('JSON LOADED!'));
}

正如您在未来链的最后一个中看到的那样它应该返回链中的任何内容,但在此之前打印“JSON LOADED!” .

但是泛型和 Future api 有一些东西我没能找到让它工作的方法,这是错误:

Unhandled exception:
type '(Map<dynamic, dynamic>) => Map<dynamic, dynamic>' is not a subtype of type '(dynamic) => FutureOr<Map<dynamic, dynamic>>'
#0      load (file:///{.../..../......}/data/data_json.dart:11:13)
#1      main (file:///{.../..../......}/data/main.dart:7:28)
#2      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

我尝试了很多不同的东西,但基本上我不明白发生了什么,飞镖不是根据泛型类型注释推断出正确的类型吗?

标签: dartfuture

解决方案


我不知道为什么它不能处理这里的类型,而是将代码更改为

Future<Map> load(String folder) {
  return File(Paths.of([folder, 'data.json']))
      .readAsString()
      .then((s) => jsonDecode(s))
      .then((v) => debug<Map>('JSON LOADED!')(v));
}

解决您的问题。我以为这应该是等效的...


推荐阅读