如何将Flutter桌面应用与Python Fast API打包为单一软件?
打包Flutter桌面应用与FastAPI服务为单一可部署应用方案
核心思路
将FastAPI服务打包为独立可执行文件,让Flutter应用启动时自动拉起该服务,最后通过打包工具将两者整合为单一安装包/可执行文件。
1. 打包FastAPI服务为独立可执行文件
使用PyInstaller将FastAPI+Uvicorn服务打包成无需Python环境的单文件:
- 安装PyInstaller:
pip install pyinstaller - 编写服务启动脚本(假设你的FastAPI入口为
main.py,新建start_server.py):import uvicorn from main import app if __name__ == "__main__": # 绑定本地回环地址,避免暴露到公网 uvicorn.run(app, host="127.0.0.1", port=8000) - 执行打包命令(覆盖Uvicorn的隐式依赖):
打包完成后,pyinstaller --onefile --hidden-import uvicorn.logging --hidden-import uvicorn.loops --hidden-import uvicorn.loops.auto --hidden-import uvicorn.protocols --hidden-import uvicorn.protocols.http --hidden-import uvicorn.protocols.http.h11 --hidden-import uvicorn.protocols.websockets --hidden-import uvicorn.protocols.websockets.wsproto --hidden-import uvicorn.server start_server.pydist目录下会生成对应平台的可执行文件(Windows为start_server.exe,Mac/Linux为start_server)。
2. 修改Flutter应用,自动启动FastAPI服务
在Flutter主入口main.dart中添加代码,启动打包好的服务,并在应用退出时关闭服务:
import 'dart:io'; import 'package:flutter/material.dart'; void main() async { Process? serverProcess; try { // 根据平台获取服务可执行文件路径 final serverPath = _getServerPath(); // 启动服务 serverProcess = await Process.start(serverPath, []); // 等待服务初始化(时间根据你的服务启动速度调整) await Future.delayed(const Duration(seconds: 2)); } catch (e) { debugPrint('API服务启动失败: $e'); // 可添加用户提示逻辑 } runApp(const MyApp()); // 监听应用生命周期,退出时关闭服务 WidgetsBinding.instance.addObserver(_LifecycleObserver(serverProcess)); } String _getServerPath() { final currentDir = Directory.current.path; if (Platform.isWindows) { return '$currentDir/start_server.exe'; } else if (Platform.isMacOS) { // macOS打包后可执行文件需放在App包的Resources目录,这里路径需对应调整 return '$currentDir/Contents/Resources/start_server'; } else { return '$currentDir/start_server'; } } class _LifecycleObserver extends WidgetsBindingObserver { final Process? serverProcess; _LifecycleObserver(this.serverProcess); @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.detached) { serverProcess?.kill(); } } } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter + FastAPI', home: Scaffold( body: Center(child: Text('应用运行中')), ), ); } }
3. 整合两者为单一部署包
Windows平台
使用Inno Setup或NSIS制作安装包:
- 将Flutter打包后的exe(
build/windows/runner/Release/xxx.exe)和FastAPI的start_server.exe放入安装包资源 - 设置安装脚本将两个文件安装到同一目录,启动项指向Flutter的exe
macOS平台
- 将FastAPI的
start_server复制到Flutter打包生成的.app包内的Contents/Resources目录 - 使用
create-dmg工具将.app包打包成dmg镜像,用户安装后直接运行.app即可
Linux平台
- 使用
dpkg-deb制作Debian包,或用AppImage打包工具 - 将Flutter可执行文件和FastAPI可执行文件放入同一目录,编写启动脚本先启动FastAPI再启动Flutter,将脚本设为启动项
关键注意事项
- 务必将FastAPI服务绑定到
127.0.0.1,禁止绑定公网IP,避免安全风险 - 测试时需验证离线环境下的运行情况,确保无依赖缺失
- 可添加服务启动超时检测逻辑,若服务未正常启动,给用户明确提示
内容的提问来源于stack exchange,提问作者Rajendra Singh
相关产品推荐
相关产品推荐

