Home > Mobile >  Issue reading string http response in flutter
Issue reading string http response in flutter

Time:09-17

I wrote a google cloud function that returns a single number. I would like to read that number on my flutter application but I am not able to do so. It looks like the flutter http dependency can only read JSON format.

I have tried formatting the response output in the cloud function but I keep getting error messages saying flask is not found. I am using Python 3.9 which, according to this link, is supposed to have flask by default. I have also tried formatting the output as dictionary and then use json.dumps(x) but that does not work either.

This function is supposed to retrieve the data:

  Future<http.Response> dataHTTP() async {
    return http.get(
      Uri.parse(
        ('https://us-east4-persuasive-yeti-325421.cloudfunctions.net/open_seats?college'  
            college.text.toUpperCase()  
            '&dept='  
            department.text.toUpperCase()  
            '&course='  
            course.text.toUpperCase()  
            '&section='  
            section.text.toUpperCase()),
      ),
    );
  }

I would like to print the output to the terminal to check that things are working. But the code snippet below returns the following: Instance of 'Future<Response>'

TextButton(
  onPressed: () async {
    print(dataHTTP().toString());
  },
  child: Text('Enter'),
)

How can I return the data itself and not the Object Instance? Is it easier to format the output in the cloud function, or handle it on client side?

CodePudding user response:

You are getting Instance of 'Future<Response>' because you are printing the toString() method of the Future object, not the response itself. When you use async and you need the result of that async task, you need to "await" for it. If you want to keep the method signature, you can await for the response in your onPressed function, like this:

TextButton(
  onPressed: () async {
    http.Response response = await dataHTTP();
    print(response.body);
  },
  child: Text('Enter'),
)

You can get more info on async programming with Dart in this codelab

CodePudding user response:

The issue I had was that the http request only contains a integer value. In order to display that value on my flutter app all I had to do is this:

TextButton(
  onPressed: () async {
    http.Response response = await dataHTTP();
    print(response.body);
  },
  child: Text('Enter'),
  • Related