Created
August 24, 2020 03:57
-
-
Save nanox77/8778b6dfa45df35b85ef632e83d619e9 to your computer and use it in GitHub Desktop.
How to parse json using async / await keywords and Future in Dart / Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:http/http.dart'; | |
main() async { | |
List<Repository> repositories = await GithubService().flutterRespositoriesUsingAsyncAwait(); | |
repositories.forEach((repository) => print(repository)); | |
} | |
main() { | |
GithubService() | |
.flutterRespositoriesUsingAsyncAwait() | |
.then((repositories) => repositories.forEach((repository) => print(repository))); | |
} | |
class GithubService { | |
final String _flutterGithubUrl = 'https://api.github.com/orgs/flutter/repos'; | |
Future<List<Repository>> flutterRespositoriesUsingAsyncAwait() async { | |
Response response = await get(_flutterGithubUrl); | |
List<dynamic> parsed = json.decode(response.body); | |
return parsed.map((json) => Repository.fromJson(json)).toList(); | |
} | |
Future<List<Repository>> flutterRespositoriesUsingFuture() { | |
return get(_flutterGithubUrl) | |
.then((response) => json.decode(response.body)) | |
.then((parsed) => parsed.map((json) => Repository.fromJson(json)).toList()); | |
} | |
} | |
class Repository { | |
final int id; | |
final String name; | |
final String avatarUrl; | |
final String htmlUrl; | |
final int stars; | |
Repository({ | |
this.id, | |
this.name, | |
this.avatarUrl, | |
this.htmlUrl, | |
this.stars, | |
}); | |
factory Repository.fromJson(Map<String, dynamic> json) { | |
return Repository( | |
id: json['id'] as int, | |
name: json['name'] as String, | |
avatarUrl: json['owner']['avatar_url'] as String, | |
htmlUrl: json['html_url'] as String, | |
stars: json['stargazers_count'] as int, | |
); | |
} | |
@override | |
String toString() { | |
return '$name has $stars stars. More info: $htmlUrl'; | |
} | |
} |
Kamryy, what is the problem? thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
same problems anyone?