Unable to send flutter GET request to python local server

Issue

I’ve made a simple flutter web app with TextField() and a Text() widget. When I press the button I expect it to send a query to the simple flask app made using python where it will returns the inverted text and I display that on the Text widget.

NOTE: Inverting text is not the actual task. Its just to check if I’m
able to get the data.

Python Code:

This code works when I run on the chrome.

#performing flask imports
from flask import Flask,jsonify
from flask.globals import request


app = Flask(__name__) #intance of our flask application 

#Route '/' to facilitate get request from our flutter app
@app.route("/api",methods=["GET"])
def function():
    d = {}
    text = str(request.args["Query"])
    text = text[::-1]
    d["query"] = text
    return jsonify(d)

if __name__ == "__main__":
    app.run()

Flutter Code:

main.dart

import 'package:flutter/material.dart';
import 'api.dart';
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String url;

  var data;

  String queryText = "Query";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("PYTHON AND FLUTTER"),
        ),
        body: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextField(
                onChanged: (value) {
                  url = "http://10.0.2.2:5000/api?Query=" + value.toString();
                },
                decoration: InputDecoration(
                    hintText: "Search Anything Here",
                    suffixIcon: GestureDetector(
                        onTap: () async {
                          data = await getData(url);
                          var decodedData = jsonDecode(data);
                          setState(() {
                            queryText = decodedData["Query"];
                          });
                        },
                        child: Icon(Icons.search))),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(
                queryText,
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

api.dart

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

Future getData(url) async {
  http.Response response = await http.get(url);
  return response.body;
}

I followed the tutorial from : This Youtube Video

I’m running the python code via Command Prompt and flutter app through VScode.

I’m getting the following errors:

Error: Expected a value of type 'Uri', but got one of type 'String'
    at Object.throw_ [as throw] (http://localhost:50523/dart_sdk.js:5348:11)
    at Object.castError (http://localhost:50523/dart_sdk.js:5319:15)
    at Object.cast [as as] (http://localhost:50523/dart_sdk.js:5635:17)
    at Function.as_C [as as] (http://localhost:50523/dart_sdk.js:5263:19)
    at getData (http://localhost:50523/packages/word_prediction/api.dart.lib.js:29:47)
    at getData.next (<anonymous>)
    at runBody (http://localhost:50523/dart_sdk.js:39211:34)
    at Object._async [as async] (http://localhost:50523/dart_sdk.js:39242:7)
    at Object.getData (http://localhost:50523/packages/word_prediction/api.dart.lib.js:28:18)
    at main._MyAppState.new.<anonymous> (http://localhost:50523/packages/word_prediction/main.dart.lib.js:422:48)
    at Generator.next (<anonymous>)
    at runBody (http://localhost:50523/dart_sdk.js:39211:34)
    at Object._async [as async] (http://localhost:50523/dart_sdk.js:39242:7)
    at http://localhost:50523/packages/word_prediction/main.dart.lib.js:421:210
    at tap.TapGestureRecognizer.new.invokeCallback (http://localhost:50523/packages/flutter/src/gestures/recognizer.dart.lib.js:203:18)
    at tap.TapGestureRecognizer.new.handleTapUp (http://localhost:50523/packages/flutter/src/gestures/tap.dart.lib.js:417:40)
    at tap.TapGestureRecognizer.new.[_checkUp] (http://localhost:50523/packages/flutter/src/gestures/tap.dart.lib.js:223:12)
    at tap.TapGestureRecognizer.new.acceptGesture (http://localhost:50523/packages/flutter/src/gestures/tap.dart.lib.js:199:23)
    at arena.GestureArenaManager.new.sweep (http://localhost:50523/packages/flutter/src/gestures/arena.dart.lib.js:222:31)
    at binding$5.WidgetsFlutterBinding.new.handleEvent (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:402:27)
    at binding$5.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:381:24)
    at binding$5.WidgetsFlutterBinding.new.dispatchEvent (http://localhost:50523/packages/flutter/src/rendering/layer.dart.lib.js:6107:13)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerEventImmediately] (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:352:14)
    at binding$5.WidgetsFlutterBinding.new.handlePointerEvent (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:325:43)
    at binding$5.WidgetsFlutterBinding.new.[_flushPointerEventQueue] (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:314:14)
    at binding$5.WidgetsFlutterBinding.new.[_handlePointerDataPacket] (http://localhost:50523/packages/flutter/src/gestures/binding.dart.lib.js:304:65)
    at Object.invoke1 (http://localhost:50523/dart_sdk.js:185426:7)
    at _engine.EnginePlatformDispatcher.__.invokeOnPointerDataPacket (http://localhost:50523/dart_sdk.js:165747:15)
    at _engine.PointerBinding.__.[_onPointerData] (http://localhost:50523/dart_sdk.js:166405:49)
    at http://localhost:50523/dart_sdk.js:166863:28
    at http://localhost:50523/dart_sdk.js:166816:16
    at http://localhost:50523/dart_sdk.js:166509:11

I don’t know what I’m doing wrong here.

Solution

Try this:

Future getData(String url) async {
  var response = await http.get(Uri.parse(url));
  return response.body;
}

Answered By – Ουιλιαμ Αρκευα

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.