70 phút
API Integration & HTTP Requests
Giới thiệu HTTP trong Flutter
Kết nối với REST APIs để fetch và send data.
http package
dependencies:
http: ^0.13.0
GET Request
import 'package:http/http.dart' as http;
Future<List<Post>> fetchPosts() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
);
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
return data.map((json) => Post.fromJson(json)).toList();
} else {
throw Exception('Failed to load posts');
}
}
POST Request
Future<Post> createPost(String title, String body) async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {'Content-Type': 'application/json'},
body: json.encode({
'title': title,
'body': body,
'userId': 1,
}),
);
if (response.statusCode == 201) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to create post');
}
}
Error Handling
try {
final posts = await fetchPosts();
setState(() {
_posts = posts;
_isLoading = false;
});
} catch (error) {
setState(() {
_error = error.toString();
_isLoading = false;
});
}
Loading States
if (_isLoading) {
return Center(child: CircularProgressIndicator());
}
if (_error != null) {
return Center(child: Text('Error: $_error'));
}
return ListView.builder(
itemCount: _posts.length,
itemBuilder: (context, index) {
return PostItem(post: _posts[index]);
},
);
Dio Package (Alternative)
dependencies:
dio: ^4.0.0
import 'package:dio/dio.dart';
final dio = Dio();
Future<void> fetchData() async {
try {
final response = await dio.get('https://api.example.com/data');
print(response.data);
} on DioError catch (e) {
print('Error: ${e.message}');
}
}