You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决真实设备无法连接本地Flask API的问题?

问题:Flask API在模拟器可正常访问,真实设备无法连接

在Android模拟器中,通过http://10.0.2.2:5000访问本地Flask API一切正常,但切换到真实设备后,使用http://127.0.0.1:5000无法建立连接。

相关代码

Flask 服务代码

from flask import Flask, request, json
from flask.json import jsonify
import requests

app = Flask(__name__)


@app.route('/temp', methods = ['GET'])
def temp_Klevin_to_celsius():
    zipcode=str(request.args['zipcode'])
    r=requests.get(
        'http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',us&appid=5e50d7b5ffd8f7551ac8e526bff04a8d')
    json_object=r.json()
    temp_k=json_object['main']['temp']
    result=round((temp_k-273.15),2)
    d={}
    d['zipcode']=str(result)
    return d

@app.route('/convert', methods = ['GET'])
def convert_currency():
    from_currency = str(request.args['from_currency']).upper()
    to_currency = str(request.args['to_currency']).upper()
    amount = float(request.args['amount'])
    response = requests.get(
        f"https://api.frankfurter.app/latest?amount={amount}&from={from_currency}&to={to_currency}")
    d={}
    d['curr']=str(response.json()['rates'][to_currency])
    return d


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

Flutter 网络请求工具函数

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

fetchdata(String url)async
{
  http.Response response =await http.get(Uri.parse(url));
  return response.body;
}

Flutter 页面代码

import 'dart:convert';


import 'package:boombest_driver/pages/function.dart';
import 'package:flutter/material.dart';

class CurrencyPage extends StatefulWidget {
  const CurrencyPage({super.key});

  @override
  State<CurrencyPage> createState() => _CurrencyPageState();
}

class _CurrencyPageState extends State<CurrencyPage> {
  String url='',fromCurrency='',toCurrency='',amount='';
  var data;
  String output='';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Currency Converter')),
      body: Center(child: Container(
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [  

              TextField(
                      onChanged: (value){
                        fromCurrency=value.toString();                
                      },
                      decoration: const InputDecoration(
                        labelText: "Convert from",
                        labelStyle: TextStyle(
                          fontSize: 25,
                        ),

                      ),
                      style: const TextStyle(
                        color: Colors.grey,
                        fontSize: 20,
                      ),

                    ),
              const SizedBox(height: 22,),

              TextField(
                      onChanged: (value){
                        toCurrency=value.toString();                
                      },
                      decoration: const InputDecoration(
                        labelText: "Convert To",
                        labelStyle: TextStyle(
                          fontSize: 25,
                        ),

                      ),
                      style: const TextStyle(
                        color: Colors.grey,
                        fontSize: 20,
                      ),

                    ),
              const SizedBox(height: 22,),

              TextField(
                      onChanged: (value){
                        amount=value.toString();                
                      },
                      decoration: const InputDecoration(
                        labelText: "Amount",
                        labelStyle: TextStyle(
                          fontSize: 25,
                        ),

                      ),
                      style: const TextStyle(
                        color: Colors.grey,
                        fontSize: 20,
                      ),

                    ),
              const SizedBox(height: 22,),
              
            TextButton(onPressed: ()async{
              if(fromCurrency!='' && toCurrency!='' && amount!=''){
                url = 'http://10.0.2.2:5000/convert?from_currency='+fromCurrency+'&to_currency='+toCurrency+'&amount='+amount;
                // url = 'http://127.0.0.1:5000/convert?from_currency='+fromCurrency+'&to_currency='+toCurrency+'&amount='+amount;
                
                data = await fetchdata(url);
                var decoded = jsonDecode(data);
                setState(() {
                  output = amount+' '+fromCurrency+' is equal to '+decoded['curr']+' '+toCurrency;
                  
                });
              }else{
                setState(() {
                  output = "Please Enter a valid data";
                });
              }
      
            }, child: const Text(
              'Convert',
              style: TextStyle(fontSize: 20),
            )),
            
            Text(output,style: TextStyle(fontSize: 40, color: Colors.green))
          ],
        ),
      )),
    );
  }
}

解决方案

  • 配置网络私有属性:按下win + R打开设置,进入「网络和Internet」-「Wi-Fi」,将当前Wi-Fi网络设为私有;
  • 修改Flask服务绑定地址:替换原启动代码
    原代码:
    if __name__ == '__main__':
        app.run(debug=True)
    
    替换为:
    if __name__ == '__main__':
        app.run(host='192.168.1.5', port=5000, debug=True, threaded=False)
    
    其中192.168.1.5是你的本地IPv4地址,可通过在Cmd中执行ipconfig命令获取;
  • 更新Flutter中的API地址:将currency文件里的http://10.0.2.2:5000替换为http://192.168.1.5:5000,确保/convert和/temp接口都完成替换。

内容的提问来源于stack exchange,提问作者Noureddin Sameer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:45:15