Flutter使用localize_it:如何避免执行build_runner前的clean与pub get操作?
解决localize_it依赖build_runner的重复命令问题
一、避免每次执行flutter clean和flutter pub get的方法
- 优先用
build_runner自带参数处理冲突:--delete-conflicting-outputs本身就是用来解决生成文件冲突的,多数场景下不需要提前执行flutter clean。如果执行build_runner命令仍报错,再排查具体缓存残留或依赖版本问题,而非直接依赖clean操作。 - 仅在依赖变更时执行
flutter pub get:如果没有修改pubspec.yaml或调整依赖版本,完全不需要每次都执行该命令,能节省大量重复操作的时间。
二、合并命令为一键执行的方案
1. 用Shell/Batch脚本实现(简单高效)
Linux/macOS:
创建localize_it.sh脚本文件,内容如下:
#!/bin/bash flutter clean flutter pub get flutter pub run build_runner build --delete-conflicting-outputs
执行chmod +x localize_it.sh赋予脚本执行权限,之后运行./localize_it.sh即可一键完成所有操作。
Windows:
创建localize_it.bat批处理文件,内容如下:
flutter clean flutter pub get flutter pub run build_runner build --delete-conflicting-outputs
双击文件或在命令行输入localize_it.bat即可执行。
2. 自定义Flutter风格命令(更贴近需求)
方式一:Dart脚本+pubspec配置
- 在项目根目录创建
tool/localize_it.dart文件:
import 'dart:io'; void main() async { await Process.run('flutter', ['clean']); await Process.run('flutter', ['pub', 'get']); await Process.run('flutter', ['pub', 'run', 'build_runner', 'build', '--delete-conflicting-outputs']); }
- 在
pubspec.yaml中添加脚本配置:
scripts: localize_it: dart tool/localize_it.dart
之后执行dart run localize_it即可完成整套操作。
方式二:系统命令别名
在Linux/macOS的终端配置文件(如.bashrc、.zshrc)中添加别名:
alias flutter-localize-it='flutter clean && flutter pub get && flutter pub run build_runner build --delete-conflicting-outputs'
保存配置后重启终端,直接输入flutter-localize-it就能一键执行所有命令。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

