Last active
May 27, 2021 18:58
-
-
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)
This file contains 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
//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