为什么toList()创建List< dynamic>在Dart? [英] Why toList() creates a List<dynamic> in Dart?

查看:69
本文介绍了为什么toList()创建List< dynamic>在Dart?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法,可以在Dart 2中正确编译.但是在运行时,出现以下错误

I have this method, which compiles with no problems in Dart 2. However at run-time I get the following error

类型' List< dynamic> '不是类型' List< ExchangeRate> '

正如您在代码中看到的那样,我在 .map()中创建并返回新的ExchangeRate对象,然后返回我期望的 rateEntries.toList()的类型为 List< ExchangeRate> ,但是似乎可以推断为类型为 List< dynamic> !!!

As you see in the code I create and return new ExchangeRate objects within .map() and then after that I return a rateEntries.toList() which I expect to be of type List<ExchangeRate>, however it seems to be inferred as type List<dynamic>!!!

@override
Future<List<ExchangeRate>> getExchangeRatesAt(DateTime time, Currency baseCurrency) async {
  final http.Client client = http.Client();
  final String uri = "some uri ...";
  return await client
    .get(uri)
    .then((response) {
      var jsonEntries = json.decode(response.body) as Map<String, dynamic>;
      var rateJsonEntries = jsonEntries["rates"].entries.toList();
      var rateEntries = rateJsonEntries.map((x) {
        return new ExchangeRate(x.value.toDouble());
      });
      return rateEntries.toList(); // WHY IS IT RETURNING A List<dynamic> here?
    })
    .catchError((e) => print(e))
    .whenComplete(() => client.close());
}

但是,如果我将其专门转换为ExchangeRate,那就没问题了.

However if I cast it specifically to ExchangeRate it would be fine.

    return rateEntries.toList().cast<ExchangeRate>();

这种转换对我来说似乎是多余的,为什么我需要它?

This casting at the end seems redundant to me, why should I need it?

推荐答案

好吧,似乎必须使用强制类型转换来完全定义类型.

Well, it seems that the cast is necessary to fully define the type.

但是,如果添加以下任何代码段,则可以避免强制转换:

But, you can avoid the cast if you add any of the following snippets:

  1. rateJsonEntries 变量提供正确的类型

List< dynamic>rateJsonEntries = jsonEntries ["rates"].entries.toList();

无论出于何种原因,这对我来说都是有效的.

For whatever reason this works in my case.

将参数类型添加到 map()方法

var rateEntries = rateJsonEntries.map< ExchangeRate>(((x){返回新的ExchangeRate(x.value.toDouble());});

这篇关于为什么toList()创建List&lt; dynamic&gt;在Dart?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆