Flutter: Performing HTTP Requests with DART
An
alternative to consume data from external data source within a Flutter APP is
through the performance of HTTP Requests.
For this
purpose, the first step is to import the http package, include a new dependency
in pubspec.yaml file.
The you
also has to include the permission to allow your APP to access internet. In
case of ANDROID app, add a this permission statement in AndroidManifest.xml.
<uses-permission
android:name="android.permission.INTERNET" />
Now you are
ready to perform HTTP requests. In a .dart file include the following
dependencies:
import 'package:http/http.dart' as http;
//perform
http request
import 'dart:convert'; //
convert response string to JSON (map)
Now you are
able to perform the HTTP request to a certain endpoint using a code like the
one in the method below:
performHTTPRequest() async {
String output="";
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
output=response.body;
var json=jsonDecode(output);
setState(() {
this.data = output;
this.title= json['title'];
});
print(response.body);
} else {
throw Exception('Failed to load data');
}
return output;
}
You may
find the complete source code on github:
https://github.com/rafaelqg/code/blob/main/http_request_fetch.dart
You may
also see a video class about how to perform the instructions described in this
post.
https://www.youtube.com/watch?v=ZEnWA8c3e_4
Comments
Post a Comment