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

  1. Add http package:
    Bash
    flutter pub add http
    
  2. 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:

  1. Construct the URL: We use Uri.parse to construct the URL with the specified ID.
  2. Make the GET request: http.get sends the request to the server.
  3. 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-catch blocks to handle potential exceptions like network errors or server errors.
  • Asynchronous Operations: The async/await syntax ensures that the code executes asynchronously, preventing UI freezes.


Comentarios

Entradas más populares de este blog

Spring Framework