I have this method, which compiles with no problems in Dart 2. However at run-time I get the following error
type '
List<dynamic>
' is not a subtype of type 'List<ExchangeRate>
'
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());
}
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?
The list is a type of datatype in Dart language that acts as an object. It can be used to store various values. In a dynamic List, the values can be of the same data or a combination of different data types(int only or combination of int and string, etc).
Creates a List<T> and adds all elements of this stream to the list in the order they arrive. When this stream ends, the returned future is completed with that list. If this stream emits an error, the returned future is completed with that error, and processing stops.
In dart and flutter, this example converts a list of dynamic types to a list of Strings. map() is used to iterate over a list of dynamic strings. To convert each element in the map to a String, toString() is used. Finally, use the toList() method to return a list.
We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.
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:
Give the correct type to the rateJsonEntries
variable
List<dynamic> rateJsonEntries = jsonEntries["rates"].entries.toList();
For whatever reason this works in my case.
Add the parameter type to the map()
method
var rateEntries = rateJsonEntries.map<ExchangeRate>((x) {
return new ExchangeRate(x.value.toDouble());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With