Flutter Http
This section will introduce how to make HTTP network requests in Flutter applications, including GET, POST requests and JSON data processing.
* * *
## Add HTTP Dependency
Add the http package in pubspec.yaml:
dependencies: http: ^1.0.0
Then run:
$ flutter pub get
* * *
## Send GET Request
## Example: GET Request
import'dart:convert';
import'package:http/http.dart'as http;
// Simple GET Request
Future fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if(response.statusCode==200){
// Parse JSON Data
final data = jsonDecode(response.body);
print('Title: ${data['title']}');
}else{
print('Request failed: ${response.statusCode}');
}
}
// GET Request with Parameters
Future searchData(String query) async {
final uri = Uri.parse('https://api.example.com/search')
.replace(queryParameters:{'q': query,'page':'1'});
final response = await http.get(uri);
if(response.statusCode==200){
final data = jsonDecode(response.body);
print('Result: $data');
}
}
* * *
## Send POST Request
## Example: POST Request
import'dart:convert';
import'package:http/http.dart'as http;
// POST Request - Send JSON Data
Future postData() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final response = await http.post(
uri,
headers:{
'Content-Type':'application/json',// Set Request Header
},
body: jsonEncode({// Convert Dart Object to JSON String
'title':'Flutter Tutorial',
'body':'Learn Flutter Network Requests',
'userId':1,
}),
);
if(response.statusCode==201){
final data = jsonDecode(response.body);
print('Created successfully: $data');
}else{
print('Request failed: ${response.statusCode}');
}
}
// POST Request - Send Form Data
Future postFormData() async {
final uri = Uri.parse('https://example.com/api/login');
final response = await http.post(
uri,
body:{
'username':'admin',
'password':'123456',
},
);
print('Response: ${response.body}');
}
* * *
## Handle JSON Data
## Example: JSON Parsing
import'dart:convert';
// Define Data Model
class Article {
final int id;
final String title;
final String body;
final User user;
Article({
required this.id,
required this.title,
required this.body,
required this.user,
});
// Parse from JSON
factory Article.fromJson(Map json){
return Article(
id: json['id'],
title: json['title'],
body: json['body'],
user: User.fromJson(json['user']),
);
}
// Convert to JSON
Map toJson(){
return{
'id': id,
'title': title,
'body': body,
'user': user.toJson(),
};
}
}
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map json){
return User(id: json['id'], name: json['name']);
}
Map toJson(){
return{'id': id,'name': name};
}
}
// Usage Example
void parseJson(){
final jsonString ='''
{
"id": 1,
"title": "Flutter Tutorial",
"body": "Learn Flutter",
"user": {"id": 1, "name": "Zhang San"}
}
''';
// Parse JSON String
final Map json = jsonDecode(jsonString);
final article = Article.fromJson(json);
print('Article ID: ${article.id}');
print('Author: ${article.user.name}');
}
* * *
## Error Handling
## Example: Complete Network Request Example
import'dart:convert';
import'package:http/http.dart'as http;
class ApiService {
// Base URL
static const String baseUrl ='https://jsonplaceholder.typicode.com';
// Generic GET Request Method
static Futureget(String endpoint) async {
try{
final response = await http.get(
Uri.parse('$baseUrl/$endpoint'),
);
return _handleResponse(response);
}catch(e){
throw ApiException('Network error: $e');
}
}
// Generic POST Request Method
static Future post(
String endpoint,
Map data,
) async {
try{
final response = await http.post(
Uri.parse('$baseUrl/$endpoint'),
headers:{'Content-Type':'application/json'},
body: jsonEncode(data),
);
return _handleResponse(response);
}catch(e){
throw ApiException('Network error: $e');
}
}
// Handle Response
static dynamic _handleResponse(http.Response response){
if(response.statusCode>=200&& response.statusCode=500){
throw ApiException('Server error', statusCode: response.statusCode);
}else{
throw ApiException(
'Request failed',
statusCode: response.statusCode,
);
}
}
}
// Custom Exception Class
class ApiException implements Exception {
final String message;
final int? statusCode;
ApiException(this.message,{this.statusCode});
@override
String toString()=>'ApiException: $message (status: $statusCode)';
}
// Usage Example
Future fetchArticles() async {
try{
final articles = await ApiService.get('posts');
print('Fetched ${articles.length} articles');
} on ApiException catch(e){
print('API Error: $e');
}
}
> In real applications, it is recommended to encapsulate network requests into a service class to uniformly handle errors, loading states, and caching logic.
YouTip