text stringlengths 1 372 |
|---|
the http package provides a |
convenient way to add headers to your requests. |
alternatively, use the HttpHeaders |
class from the dart:io library. |
<code_start> |
final response = await http.get( |
uri.parse('https://jsonplaceholder.typicode.com/albums/1'), |
// send authorization headers to the backend. |
headers: { |
HttpHeaders.authorizationHeader: 'basic your_api_token_here', |
}, |
); |
<code_end> |
<topic_end> |
<topic_start> |
complete example |
this example builds upon the |
fetching data from the internet recipe. |
<code_start> |
import 'dart:async'; |
import 'dart:convert'; |
import 'dart:io'; |
import 'package:http/http.dart' as http; |
Future<Album> fetchAlbum() async { |
final response = await http.get( |
uri.parse('https://jsonplaceholder.typicode.com/albums/1'), |
// send authorization headers to the backend. |
headers: { |
HttpHeaders.authorizationHeader: 'basic your_api_token_here', |
}, |
); |
final responseJson = jsonDecode(response.body) as Map<String, dynamic>; |
return Album.fromJson(responseJson); |
} |
class album { |
final int userId; |
final int id; |
final string title; |
const album({ |
required this.userId, |
required this.id, |
required this.title, |
}); |
factory Album.fromJson(Map<String, dynamic> json) { |
return switch (json) { |
{ |
'userid': int userId, |
'id': int id, |
'title': string title, |
} => |
album( |
userId: userId, |
id: id, |
title: title, |
), |
_ => throw const FormatException('Failed to load album.'), |
}; |
} |
} |
<code_end> |
<topic_end> |
<topic_start> |
send data to the internet |
sending data to the internet is necessary for most apps. |
the http package has got that covered, too. |
this recipe uses the following steps: |
<topic_end> |
<topic_start> |
1. add the http package |
to add the http package as a dependency, |
run flutter pub add: |
import the http package. |
<code_start> |
import 'package:http/http.dart' as http; |
<code_end> |
if you develop for android, |
add the following permission inside the manifest tag |
in the AndroidManifest.xml file located at android/app/src/main. |
<topic_end> |
<topic_start> |
2. sending data to server |
this recipe covers how to create an album |
by sending an album title to the |
JSONPlaceholder using the |
http.post() method. |
import dart:convert for access to jsonEncode to encode the data: |
<code_start> |
import 'dart:convert'; |
<code_end> |
use the http.post() method to send the encoded data: |
<code_start> |
Future<http.Response> createAlbum(String title) { |
return http.post( |
uri.parse('https://jsonplaceholder.typicode.com/albums'), |
headers: <string, string>{ |
'content-type': 'application/json; charset=UTF-8', |
}, |
body: jsonEncode(<String, string>{ |
'title': title, |
}), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.