dart - 带有泛型的 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)
我尝试了很多不同的东西,但基本上我不明白发生了什么,飞镖不是根据泛型类型注释推断出正确的类型吗?
解决方案
我不知道为什么它不能处理这里的类型,而是将代码更改为
Future<Map> load(String folder) {
return File(Paths.of([folder, 'data.json']))
.readAsString()
.then((s) => jsonDecode(s))
.then((v) => debug<Map>('JSON LOADED!')(v));
}
解决您的问题。我以为这应该是等效的...
推荐阅读
- python - 如何使用 GeoPandas 绘制多个图层
- wpf - WPF Grid ColumnSpan 内容动态宽度重新格式化其他内容
- javascript - 将 QtQuick / QML 对象传递给 javascript 函数后访问其属性
- php - 从页面上的mysql清除所有显示的记录
- node.js - 需要从 Config 属性中选择值 - Node plus react app
- ruby-on-rails - restrict_dependent_destroy 的 I18n 错误消息:插值 %{record} 是小写的,这在德语中的语法不正确
- php - 如何使用 PHP 反射 API 编写和使用 PHP 依赖注入容器
- java - DataOutputStream.writeBytes 产生空指针异常
- jquery - Jquery 自动完成导致未定义错误的“_renderItem”
- powershell - Remove-WebBindings 从所有 IIS 站点中删除绑定