Jonah.Checketts
Jonah.Checketts

Reputation: 64

Connecting my Python backend with my Flutter Frontend using Flask

So currently I am trying to learn how to connect a flutter front end with a Python backend using flask and I am making a basic project where you basically input a number in the flutter app the number you input being the index of a list I have stored in my python app the python app will then return the number at the index you specified and it will be displayed on the screen. The issue I am having is that when I run the applications the flutter application just displays an error message. I have tried a whole bunch of things and can't figure out what is wrong

Here is the link to the screenshot of my Flutter App (Includes error message received from the server):

https://i.sstatic.net/xI4iM.jpg

Here is my Python Code

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)
myList = [3,4,8,1,9,4,2,0,2,9,3,8,4,7,2,7,0,1]

@app.route('/', methods = ['GET'])
class Update(Resource):
    def get(self,pos):
        if(pos > len(myList)):
            return {"num" : "invalid number: out of list range"}
        else:
            return {"num": str(myList[pos])}
        

api.add_resource(Update, "/Update/<int:pos>")

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

here is my Flutter Code:

import 'dart:async';
import 'dart:convert';

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

Future<Entry> fetchEntry() async {
  final response =
      await http.get('https://127.0.0.1:5000/Update/3');

  if (response.statusCode == 200) {
    return Entry.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load Entry');
  }
}

class Entry {
  final String number;

  Entry({this.number});

  factory Entry.fromJson(Map<String, dynamic> json) {
    return Entry(
      number: json['num'],
    );
  }
}

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<Entry> futureEntry;

  @override
  void initState() {
    super.initState();
    futureEntry = fetchEntry();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Entry>(
            future: futureEntry,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.number);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

Also I have double checked my dependencies in my pubspec.yaml file and AndroidManifest.xml file so that shouldn't be the issue. Any help would be greatly appreciated, thanks.

EDIT: for clarification I am using and android emulator for this and have tried using a different ip address for my flutter get request (I found the ip address when trying to figure out how to fix this problem and it said that ip address needs to be used for android emulators) but it still returned the same error when I did that.

Upvotes: 1

Views: 10618

Answers (2)

Jonah.Checketts
Jonah.Checketts

Reputation: 64

I figured out the solution:

for my get request I need to be using an IP address that can be used by android the IP address that android uses is 10.0.2.2 I found this solution on this stack overflow post:

How to connect to my http://localhost web server from Android Emulator

Upvotes: 1

KilianAlias
KilianAlias

Reputation: 84

Not exactly sure why this is throwing this error as you do specify the port as 5000, but a simple solution would be to change the flask port to 50162.

if __name__ == '__main__':
  app.run(debug=True, host='0.0.0.0', port=50162)

EDIT:

On further review, you might want to change your http request in the flutter code to http, not https.

Upvotes: 2

Related Questions