微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Flask 将我的 Python 后端与我的 Flutter 前端连接起来

如何解决使用 Flask 将我的 Python 后端与我的 Flutter 前端连接起来

所以目前我正在尝试学习如何使用 Flask 将颤振前端与 Python 后端连接起来,我正在制作一个基本项目,您基本上在颤振应用程序中输入一个数字,您输入的数字是列表的索引我已将python应用程序存储在我的python应用程序中,然后python应用程序将返回您指定的索引处的数字,并将其显示在屏幕上。我遇到的问题是,当我运行应用程序时,Flutter 应用程序只显示一条错误消息。我已经尝试了一大堆东西,但不知道哪里出了问题

这是我的 Flutter 应用程序截图的链接包括从服务器收到的错误消息):

https://imgur.com/a/K6KYRAu

这是我的 Python 代码

from flask import Flask
from flask_restful import Api,Resource

app = Flask(__name__)
api = Api(app)
myList = [3,4,8,1,9,2,3,7,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)

这是我的 Flutter 代码

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();
            },);
  }
}

此外,我还仔细检查了 pubspec.yaml 文件和 AndroidManifest.xml 文件中的依赖项,因此这应该不是问题。任何帮助将不胜感激,谢谢。

编辑:为了澄清起见,我为此使用了 android 模拟器,并尝试为我的 Flutter get 请求使用不同的 ip 地址(我在试图找出解决此问题的方法时找到了 ip 地址,它说该 ip 地址需要用于 android 模拟器)但是当我这样做时它仍然返回相同的错误

解决方法

不确定为什么会在您将端口指定为 5000 时引发此错误,但一个简单的解决方案是将烧瓶端口更改为 50162。

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

编辑:

在进一步审查中,您可能希望将 flutter 代码中的 http 请求更改为 http,而不是 https。

,

我想出了解决办法:

对于我的获取请求,我需要使用可由 android 使用的 IP 地址,android 使用的 IP 地址是 10.0.2.2 我在此堆栈溢出帖子中找到了此解决方案:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。