Search code examples
flutterhttpdartflutter-web

How to make a get inside a form button OnPressed() in flutter


I want to make a get call inside the onPressed function of a form.

I have a service that make a post and return the response.body:


    Future<String> getItems() async {
        final response = await http.get(Uri.parse('$baseUrl/edicios'));
        if (response.statusCode == 200) {
          return response.body;
        }
    }

And here in the onPressed we call that function:

    onPressed: () {
      if (_formKey.currentState.validate()) {
        futureString = resource.MyHttpService().getItems();
        print(futureString);
    }

I have read the flutter doc to make gets and posts but it's confusing. If someone can just explain how it works.


Solution

  • Since your getItems() function is a future, you will need to await the response before printing it. This also means that your onPressed function needs to use the 'async' keyword:

    onPressed: () async {
          if (_formKey.currentState.validate()) {
            futureString = await resource.MyHttpService().getItems();
            print(futureString);
        }
    
    

    You can read more about async/await here.