Skip to content

Instantly share code, notes, and snippets.

@nanox77
Created August 24, 2020 03:57
Show Gist options
  • Save nanox77/8778b6dfa45df35b85ef632e83d619e9 to your computer and use it in GitHub Desktop.
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
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
Copy link

kamryy commented Mar 11, 2023

same problems anyone?

@nanox77
Copy link
Author

nanox77 commented Mar 13, 2023

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