Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make HTTP Request work in Flutter web?

I am trying to fetch data from My site link: http://mrmatjar.com/kaka/dataaza.php

Here is my code

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:mrmatjar_afflite/shopobj.dart';
class Operations{
 static Future<List<ShopObj>> loly() async{
    List<ShopObj> ak= new List<ShopObj>();
      var res = await http.get(Uri.encodeFull("https://mrmatjar.com/kaka/dataaza"),headers: {"Accept":"application/json"});

    print(res);
    var v = json.decode(x.body);
    for(var h in v){
        ak.add(new ShopObj(h['title'], h['cost'], h['earn'], h['image']));
    }
    return ak;
  }
}

But it is not working. when I run it the Web app Breaks and when I use Break point it shows file call by blinding.dart

like image 897
Y.A.D Avatar asked Oct 25 '19 10:10

Y.A.D


2 Answers

I have the same problem. It has to do with CORS. I added this to my server of the backend

sudo a2enmod headers

sudo nano /etc/apache2/mods-enabled/headers.conf

modify like this:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

then restart apache2

sudo service apache2 restart
like image 82
Hairy Ass Avatar answered Oct 12 '22 10:10

Hairy Ass


Welcome to stack overflow :).

First:

I see some typo error in your code.

var v = json.decode(x.body); should be

var v = json.decode(res.body);

Second:

Once you fix the above you might face Cross Origin Request(CORS) error which may be because you have not set this up in your server. Especially if your flutter web application is not running in the same domain as the server where you api is running. Even if its on the same machine, you will have to allow the request from certain domain and ports. If you are not aware of CORS you can read here.

Third:

As I see you are processing the response without checking the statusCode of the response it would still lead to an error when you try to decode the response.

I have a simple running example here based on the DOGs public api.

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class HttpRequestDemo extends StatefulWidget {
  @override
  _HttpRequestDemoState createState() => _HttpRequestDemoState();
}

class _HttpRequestDemoState extends State<HttpRequestDemo> {
  String imageUrl = "";

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: <Widget>[
        Center(
          child: Image.network(
            imageUrl,
            height: MediaQuery.of(context).size.height / 3,
            width: MediaQuery.of(context).size.width / 3,
          ),
        ),
        FloatingActionButton(
          child: Icon(Icons.cloud_download),
          onPressed: () {
            fetchData();
          },
        )
      ],
    ));
  }

  fetchData() async {
    final res = await http.get("https://dog.ceo/api/breeds/image/random");

    if (res.statusCode == 200) {
      var v = json.decode(res.body);
      setState(() {
        imageUrl = v['message'];
      });
    }
  }
}

This app will show a new dog photo every time you press the floating action button as shown below which is based on the response from the api.

enter image description here enter image description here

like image 6
Abhilash Chandran Avatar answered Oct 12 '22 10:10

Abhilash Chandran