flutter simple get request code example
Example 1: flutter http request
import 'package:http/http.dart' as http;
var url = Uri.parse('https://example.com/whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
print(await http.read('https://example.com/foobar.txt'));
Example 2: flutter http request
class UserAgentClient extends http.BaseClient {
final String userAgent;
final http.Client _inner;
UserAgentClient(this.userAgent, this._inner);
Future<http.StreamedResponse> send(http.BaseRequest request) {
request.headers['user-agent'] = userAgent;
return _inner.send(request);
}
}
Example 3: flutter http request
var client = http.Client();
try {
var uriResponse = await client.post(Uri.parse('https://example.com/whatsit/create'),
body: {'name': 'doodle', 'color': 'blue'});
print(await client.get(uriResponse.bodyFields['uri']));
} finally {
client.close();
}
Example 4: how to perform get request in flutter
import 'package:http/http.dart' as http;
import 'dart:convert';
class API
{
static String BASE_URL = 'https://some-url/api/';
static Future<List<ExampleData>> getRequest() async {
Response res = await http.get(BASE_URL+'example');
if (res.statusCode == 200) {
List<dynamic> body = jsonDecode(res.body);
}
}
}
Example 5: http request from flutter
Future<Album> createAlbum(String title) async {
final response = await http.post(
Uri.https('jsonplaceholder.typicode.com', 'albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
if (response.statusCode == 201) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}