skip to Main Content

I searched tutorials and library documentations which I already followed the sample codes using either Dio or Http. However, I don’t know why I cannot get a response from calling the api. There is no error and any message allows me to debug. I read the logging from cloudwatch for the api gateway. There is no trigger. The app cannot be processed any more after calling the api as I use await for waiting for the response. How should I fix it?

  Future<void> makeGetRequest() async {
    try {
      const url =
          'https://918pynqzta.execute-api.ap-southeast-1.amazonaws.com/dev/getAllElderly';

      final uri = Uri.parse(url);

      final response = await http.get(uri);
      print(response);
    } catch (e) {
      print('Error: $e');
    }
  }
ElevatedButton(
                        onPressed: () async {
                          await makeGetRequest();
                        },)

2

Answers


  1. The print(response) statement may not display the response body directly, if you are expecting JSON data. For that reason
    try this code for call get api with http

    import 'package:http/http.dart' as http;
    Future<void> makeGetRequest() async {
      try {
        const url = 'https://918pynqzta.execute-api.ap-southeast-1.amazonaws.com/dev/getAllElderly';
        final response = await http.get(Uri.parse(url));
    
        if (response.statusCode == 200) {
          var jsonResponse = jsonDecode(response.body);
          print('Response body: $jsonResponse');
        } else {
          print('Response body: ${response.body}');
        }
      } catch (e) {
        print('Error: $e');
      }
    }
    
    Login or Signup to reply.
  2. You can use POSTMAN to check API response.

    Also Flutter has Dio package for APIs.

    dio api example

    first import

    import 'package:dio/dio.dart';
    

    Initialize dio

    final dio = Dio();
    

    use this code for getting api response.

    void getHttp() async {
      final response = await dio.get('https://dart.dev');
      print(response);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search