Reputation: 4582
I'm trying to get the AngularDart tutorial to work. I've changed the name of the class and am calling a real server. The data in not making back to the list. I suspect the problem is in this code:
final artists = _extractData(response)
.map((value) => new Artist.fromJson(value))
.toList();
I want to break it down to separate statement, but I can't find any reference to .map in an Internet search. It's not a method on the map collection. How could this be broken apart?
The full method is:
Future<List<Artist>> getArtists() async {
await HttpRequest.request(_artistsUrl, requestHeaders: headers).then((response) {
final artists = _extractData(response)
.map((value) => new Artist.fromJson(value))
.toList();
return artists;
});
}
The called methods are:
dynamic _extractData(HttpRequest req) {
Map data = JSON.decode(req.responseText);
return data;
}
and:
factory Artist.fromJson(Map<String, dynamic> artist) =>
new Artist(_toInt(artist['id']),
artist['first_name'],
artist['last_name'],
artist['notes'],
artist['primary_instrument'],
artist['other_instruments'],
artist['birth_year'],
artist['death_year']
);
The caller of getArtists is:
class DashboardComponent implements OnInit {
List<Artist> artists;
final ArtistService _artistService;
final Router _router;
DashboardComponent(this._artistService, this._router);
Future<Null> ngOnInit() async {
artists = (await _artistService.getArtists());
print("Dashboard Length: ${artists.length}"); // this crashes
}
}
I rewrote getArtists:
Future<List<Artist>> getArtists() async {
HttpRequest response = await HttpRequest.request(url, requestHeaders: headers);
List data = JSON.decode(response.responseText);
final artists = data
.map((value) => new Artist.fromJson(value))
.toList();
return artists;
}
I rolled up the extractData method. The real problem was with the "return artists" being in the inner code block. As a result, it didn't get returned to the caller of getArtists. This problem is also covered in this question making this question somewhat redundant.
Upvotes: 0
Views: 63
Reputation: 1583
The problem is that you are using .then
of returned by HttpRequest.request
Future, and its callback parameter is called asynchronously. So the Future is completed, but resulting list is not filled yet. await
is shorthand for .then
, try to save await HttpRequest.request
resulting response to variable and move the callback right behind it.
Upvotes: 1
Reputation: 657288
I think the problem is that _extractData()
should return a List<Map>
where each item is a serialized Artist
A List
also has a map()
method.
dynamic _extractData(HttpRequest req) {
List data = JSON.decode(req.responseText);
return data;
}
would make this code work
final artists = _extractData(response)
.map((value) => new Artist.fromJson(value))
.toList();
but that depends on what response
actually looks like.
Upvotes: 3