Search code examples
flutter

Cannot get any response from HTTP API


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();
                        },)

Solution

  • 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');
      }
    }