Dart → .exe
:Flutter 桌面與純命令行雙軌編譯完全指南
關鍵詞:Dart、Flutter、Windows、可執行文件、桌面端、CLI、交叉編譯
1. 前言
很多開發者以為 Dart 只能跑在 AOT 移動端或 Web 端,其實 官方工具鏈早已支持一鍵輸出 Windows 原生 .exe
。
根據有無 UI,可分為兩條路線:
路線 | 產物 | 典型場景 | 本文定位 |
---|---|---|---|
Flutter 桌面 | 帶 UI 的 .exe | 本地工具、管理后臺 | 步驟 + 踩坑 |
純 Dart CLI | 單文件 .exe | 數據處理、自動化腳本 | 進階優化 |
2. 路線 A:Flutter 桌面應用 → .exe
2.1 環境 checklist
- Flutter SDK ≥ 3.19(穩定版)
- Visual Studio 2022 “使用 C++ 的桌面開發” 工作負載
- PowerShell 管理員權限運行一次:
flutter doctor --windows
出現 ? Visual Studio
即可。
2.2 開啟 Windows 支持
flutter config --enable-windows-desktop
執行后項目根目錄自動生成 windows/
文件夾。
2.3 編譯命令
模式 | 命令 | 產物路徑 | 特點 |
---|---|---|---|
調試 | flutter build windows --debug | build/windows/x64/debug/runner/Runner.exe | 含符號、幾十 MB、可斷點 |
發布 | flutter build windows --release | build/windows/x64/release/runner/Runner.exe | 優化體積、無符號、可分發 |
2.4 分發注意
- 不要只拷
.exe
!
同級*.dll
、data/
必須一起打包,zip 發給用戶。 - 改圖標/版本 → 編輯
windows/runner/Runner.rc
:IDI_APP_ICON ICON "resources\\my_icon.ico"
- 需要管理員權限 → 在
Runner.rc
把requestedExecutionLevel level="requireAdministrator"
3. 路線 B:純 Dart CLI → 單文件 .exe
3.1 環境
僅安裝 Dart SDK 即可(無需 Flutter)。
https://dart.dev/get-dart
3.2 示例腳本
bin/data_processor.dart
import 'dart:io';void main(List<String> args) {if (args.isEmpty) {stderr.writeln('用法: data_processor.exe <file>');exitCode = 1;return;}final file = File(args.first);print('行數: ${file.readAsLinesSync().length}');
}
3.3 一鍵編譯
dart compile exe bin/data_processor.dart -o bin/data_processor.exe
產物:單文件 bin/data_processor.exe
(5-10 MB),雙擊或命令行均可執行。
3.4 體積優化 & 交叉編譯
需求 | 命令 |
---|---|
再小一點 | dart compile exe --no-snapshot |
Linux → Windows | dart compile exe --target-os windows (需 mingw-w64) |
4. 兩種路線對比速覽
維度 | Flutter 桌面 .exe | 純 Dart CLI .exe |
---|---|---|
依賴 | 多 DLL 必須同目錄 | 單文件,0 依賴 |
體積 | 10-50 MB(含 UI 引擎) | 5-15 MB(僅運行時) |
入口 | main() + Widget | main() + 命令行參數 |
編譯依賴 | Flutter + VS 構建工具 | 僅 Dart SDK |
典型場景 | 圖形化工具、本地后臺 | 腳本、批量處理、安裝器 |
5. 最佳實踐小結
- 先選場景再選路線 → 有 UI 直接 Flutter,無 UI 直接
dart compile exe
。 - Flutter 發布切記整包壓縮;CI 里加一步
zip -r windows.zip build/windows/x64/release/runner/*
。 - CLI 工具發布到 GitHub Releases 時,同時提供
data_processor.exe
與data_processor-macos
等多平臺單文件,體驗極佳。 - 規則納入版本控制:
.cursorrules
里加一條:- 所有 Dart CLI 必須提供 `dart compile exe` 產物 - Flutter 桌面禁止單獨上傳 Runner.exe
6. 一鍵模板倉庫
GitHub 模板已備好:
https://github.com/yourname/dart-to-exe-template
含 Flutter 桌面 + CLI 雙示例,Actions 自動 Release,拿去即用。
🎉 現在就把你的 Dart 代碼編譯成 .exe
發給你的 Windows 小伙伴吧!如果本文幫到你,歡迎點個 Star 并分享。