我正在尝试使用python(flask)作为后端在Flatter中建立连接

2024-06-01 14:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我解决这个错误吗…
我尝试了许多不同的代码,但到目前为止都没有任何效果…
我也尝试过在模拟器中的代理服务器上运行,但没有成功
以下是颤振文件-:

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

class New extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: InkWell(
        child: Container(
          child: Column(
            children: [
              Center(
                child: Text('hello', style: TextStyle(fontSize: 50.0)),
              ),
              SizedBox(height: 50.0,),
              Center(
                child: Text('This is new', style: TextStyle(fontSize: 25.0)),
              ),
            ],
          ),
        ),
        onTap: (){
          news();
        },
      ),
    );
  }


  Future<http.Response> news() async
  {
    String url = 'http://127.0.0.1:8000/getMenuData'; //192.168.0.105:5000 another port that i tried        
    var body;
    print('Start toh hua');
    var bodyEncode = json.encode(body);
    Map<String, String> Headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };
    print('heyyyy');
    final response = await http.get(url);
    print('byeeee');
    final responseJson = json.decode(response.body);
    print('done bhi ho gaya');
    print(responseJson);
    return response;
}

}

以下是我要连接的main.py文件-:


from flask import Flask, render_template, request, redirect, url_for, jsonify

app = Flask(__name__)

@app.route('/', methods = ['GET'])
def getMenuData():    
    # if request.method == 'GET':
    #     return jsonify(menuData)
    print('hello')
    return 'Success ho gaya'
    # return jsonify ({'name':'Success'})





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


运行此文件后出现的错误是-:


Performing hot reload...
Syncing files to device sdk gphone x86...
Reloaded 8 of 716 libraries in 2,024ms.
I/flutter (20787): Started
I/flutter (20787): heyyyy
E/flutter (20787): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 45448
E/flutter (20787): 

//这是我现在试图运行的完整代码,但它不起作用


Tags: 文件importjsonchildhttpurlstringreturn
1条回答
网友
1楼 · 发布于 2024-06-01 14:34:15

首先,你没有发送标题

我认为url是错误的,应该是“/”而不是函数名

如果这些都不起作用,你应该尝试通过邮递员发送请求,看看问题出在哪里

相关问题 更多 >