How to Make HTTP Request to In Flutter Web?

3 min read
How to Make HTTP Request to In Flutter Web
How to Make HTTP Request to In Flutter Web

Most apps now a day require to fetch data from the internet. HTTP package provides the simplest way to fetch data from the internet. So in this article, we will take a deep dive into learning how to make an HTTP request to the Flutter Web.聽

How to Make an HTTP Request to In Flutter Web?

When we try to connect the flutter web app I created to the MySQL database and localhost using the HTTP package.聽 We connect with the below code snippet.

getMethod()async{
  String theUrl = 'https://localhost/fetchData.php';
  var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
  var responsBody = json.decode(res.body);
  print(responsBody);
  return responsBody;

}

You can also add the code below to your PHP file like shown in the below snippet:

<?php
require('connection.php');
header("Access-Control-Allow-Origin: *");
....
code goes here
....
?>

For accessing a website made by flutter basically, you are calling a JS script.

Which is, in this case, is CORS – Cross-Origin Resource Sharing.

Add the below code to your website’s .htaccess file

<ifModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www.)?(localhost:55538|somedomain.com)$" AccessControlAllowOrigin=$0
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header always set Access-Control-Allow-Methods: "GET,POST,PUT,DELETE,OPTIONS"
</ifModule>

By adding this will now grant access to your flutter website to hit requests to your APIs.

Lots of amazing content coming up your way!! Stay Tuned!!!!

Conclusion:

Thanks for being with us on a Flutter Journey !!!

So in this article, we will go through how to make an HTTP request to the Flutter Web.

Let us know in the comments right below, which methods you have used previously for the same. Also, Don’t forget to drop your valuable feedback 馃檪

Let us know if you have any doubts further about Flutter Development!!! We would love to assist you.

Keep Learning !!! Keep Fluttering !!! Stay Connected !!!

Flutter Agency聽is our portal Platform dedicated to聽Flutter Technology聽and聽Flutter Developers. The portal is full of cool resources from Flutter like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

Flutter Agency聽is one of the most popular online portals dedicated to聽Flutter Technology聽and daily thousands of unique visitors come to this portal to enhance their knowledge on聽Flutter.

 

3 comments

  1. I take it the CORS is needed if you are accessing a different domain from which it was launched? Presumably if you have your server code on the same domain that it was launched from you wouldn鈥檛 need to do that?

Leave a Reply