Skip to content

Instantly share code, notes, and snippets.

@tahaak67
Last active May 27, 2021 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tahaak67/3951dcd816feaf769cbe44d4105ab5ac to your computer and use it in GitHub Desktop.
Save tahaak67/3951dcd816feaf769cbe44d4105ab5ac to your computer and use it in GitHub Desktop.
How to make Rest api request and save data to object in Flutter(android studio)
//Dependencies
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
//Album = Object/Class name
//fetchAlbum() = function name
//Gnerate dart class from json using JsonToDart for Android Studio https://plugins.jetbrains.com/plugin/12562-jsontodart-json-to-dart-/
Future<Album> fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.map(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment