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.
David Bolton
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’t need to do that?
Somyarajsinh jadeja
Yes if the server code is on the same domain as the client then we don’t need CORS.
tatianagolin
olá boa tarde
Mas em um projeto flutter, onde fica gravado o arquivo .htaccess ?
É na pasta web do projeto ?