Dart新手求助:VSCode中如何实现保存代码时自动运行程序
Hey there! Great question—VSCode absolutely supports auto-restarting your Dart scripts when you save files, just like nodemon does for Node.js. Since you're already set up with Dart, Flutter, and VSCode, here are the most straightforward ways to get this working:
Option 1: Use Dart's Built-in Watch Mode (Recommended)
Dart 2.14+ comes with a native watch mode that automatically restarts your program when files change—no extra tools needed:
- Via Terminal: Open VSCode's integrated terminal and run:
From now on, every time you save adart run --watch your_main_file.dart.dartfile, your program will restart instantly. - Via Debug Panel: If you prefer launching from the debug sidebar, edit your
.vscode/launch.jsonfile to add this configuration:
Select this new configuration in the debug panel, hit play, and you’re good to go.{ "version": "0.2.0", "configurations": [ { "name": "Dart (Auto-Restart)", "type": "dart", "request": "launch", "program": "your_main_file.dart", "args": ["--watch"] } ] }
Option 2: VSCode Tasks + File Watcher
For more control over the workflow, you can use VSCode’s task system paired with a file-watching extension:
- Open the command palette (Ctrl+Shift+P / Cmd+Shift+P), search for Tasks: Configure Task, then choose Create tasks.json file from template → Others.
- Replace the default
tasks.jsoncontent with this:{ "version": "2.0.0", "tasks": [ { "label": "Run Dart Auto-Restart", "type": "shell", "command": "dart run your_main_file.dart", "problemMatcher": [], "isBackground": true, "presentation": { "panel": "shared", "reveal": "always" } } ] } - Install the File Watcher extension for VSCode, then configure it to trigger the "Run Dart Auto-Restart" task whenever a
.dartfile is saved.
Option 3: Use Nodemon Directly
Since you’re familiar with nodemon from Node.js, you can repurpose it for Dart too:
- Make sure nodemon is installed globally:
npm install -g nodemon - Create a
nodemon.jsonfile in your project root:{ "watch": ["*.dart"], "exec": "dart run your_main_file.dart", "ext": "dart" } - Run
nodemonin VSCode’s terminal, and it’ll restart your Dart program every time you save a file.
I’d start with Option 1 first—it’s the simplest, official solution that doesn’t require any extra extensions or npm packages. Happy coding!
内容的提问来源于stack exchange,提问作者raju

