Anshul Raj
Anshul Raj

Reputation: 63

How to fetch data from a server running on localhost in flutter?

I wrote an API in python and I'm running it on http://127.0.0.1:5000. (Using Flask. Also, I'm currently running it on a development server for testing purposes)

But when I tried to get the response using the http package in Flutter, I got an XMLHttpRequest error.

void api() async {
  const String url = "http://127.0.0.1:5000/dosomething?query=This doesn't work!"; # this is an example
  Response response = await get(url);
  print(response.body); # I'm printing this for testing
}

Note: I have checked the URL too, it works.

What could be the problem? And how to fix it?

Important - The following answers work when I try with an API running on the web (in this case, WorldTimeAPI). But, when I try with my code, it somehow doesn't work. Although it works perfectly fine when I manually test it.

This is a simplified version of my API code -

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/dosomething', methods = ['GET'])
def API():
     result = {}
     result['result'] = user_input = str(request.args['query'])
     return jsonify(result)

Upvotes: 2

Views: 3898

Answers (2)

Boris Grigorov
Boris Grigorov

Reputation: 408

I'm not sure what function get does, but use http like this:

import 'package:http/http.dart' as http; //Import in the beginning of file

void api() async {
  const String url = 'http://127.0.0.1:5000/dosomething?query=This doesn't work!';
  var response = await http.get(url);
  print(response.body);
}

Upvotes: 1

Shubham Narkhede
Shubham Narkhede

Reputation: 2130

You have to first import this

import 'package:http/http.dart' as http;

then for API call pass your HTTP extension and then pass your body type like post or get

  Future api() async {
    const String url = 'http://127.0.0.1:5000/dosomething?query=This doesn't work!';
    Response response = await http.get(url);  // here i passed http.get
    print(response.body); // You should get your result
  }

Upvotes: 1

Related Questions