Calling a Spring Boot REST API from Flutter
Get Rest
GET request that expects an integer ID as a path variable. It returns a String response.
Setting Up Flutter Project
- Add
httppackage:Bashflutter pub add http - Import necessary libraries:
Dart
import 'package:http/http.dart' as http; import 'dart:convert';
Making the HTTP Request
Here's a basic example of how to make a GET request to your Spring Boot endpoint:
Dart
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<String> fetchData(int id) async {
final response = await http.get(Uri.parse('http://your_server_address/personas/get/$id'));
if (response.statusCode == 200) {
return response.body; // Assuming the response is a JSON string
} else {
throw Exception('Failed to load data');
}
}
// Usage:
void main() async {
int id = 123; // Replace with the desired ID
String data = await fetchData(id);
print(data);
}
Explanation:
- Construct the URL: We use
Uri.parseto construct the URL with the specified ID. - Make the GET request:
http.getsends the request to the server. - Handle the response:
- If the status code is 200 (OK), we parse the response body.
- Otherwise, we throw an exception.
Handling JSON Responses
If your Spring Boot endpoint returns a JSON response, you can parse it using Dart's jsonDecode function:
Dart
Map<String, dynamic> data = jsonDecode(response.body);
// Access data using data['key']
Error Handling and Asynchronous Operations
- Error Handling: Use
try-catchblocks to handle potential exceptions like network errors or server errors. - Asynchronous Operations: The
async/awaitsyntax ensures that the code executes asynchronously, preventing UI freezes.
Comentarios
Publicar un comentario