上一篇《Flutter Android 工程結構及應用層編譯源碼深刻分析》咱們分析了 Flutter Android 相關的應用層主要編譯流程,其中分析到底層本質命令工具【Flutter SDK 下bin/flutter
編譯命令分析】小節時只提到,咱們執行任何 flutter 命令的本質都是把參數傳遞到了FLUTTER_SDK_DIR/packages/flutter_tools/bin/flutter_tools.dart
源碼的 main 方法中,沒有對這裏面進行深刻分析。本文要作的事就是層層遞進揭開這裏的本質,並與上篇呼應解釋編譯產物的由來。java
經過flutter -h
命令咱們能夠直觀全局感覺都支持哪些參數,有些參數還有子參數。咱們所執行的全部參數本質都走進了下面模塊的源碼入口中。 所以咱們若是直接想從源碼方式使用 flutter tools,則能夠直接當前目錄中以下命令:android
# ARGS 就是一堆參數,譬如咱們上篇的 build apk
dart bin/flutter_tools.dart ARGS
複製代碼
若是想從新生成 Flutter Tools snapshot,能夠直接當前目錄中執行以下命令:shell
rm ../../bin/cache/flutter_tools.stamp ../../bin/cache/flutter_tools.snapshot
複製代碼
這樣就成功刪除了上篇中 shell 腳本調用的 Flutter Tools snapshot,而後在執行時會自動從新生成一個。緩存
上面既然交代了整個背景,那麼咱們接下來就基於 Flutter SDK 入口packages/flutter_tools/bin/flutter_tools.dart
開始分析,整個分析繼續承接上篇flutter build apk
命令,以下:bash
//一、導入packages/flutter_tools/lib/executable.dart文件
import 'package:flutter_tools/executable.dart' as executable;
//二、入口重點,執行executable.main方法,並將咱們`build apk`參數傳入
void main(List<String> args) {
executable.main(args);
}
複製代碼
接下來咱們去packages/flutter_tools/lib/executable.dart
看看他的 main 方法,以下:markdown
Future<void> main(List<String> args) async {
//一堆參數解析判斷啥的,譬如解析flutter doctor的doctor參數啥的
......
//一、重點!runner的本質是import 'runner.dart' as runner;
// 本質就是調用run方法的各類參數傳遞,重點關注第一個和第二個參數便可
await runner.run(
args,
() => generateCommands(
verboseHelp: verboseHelp,
verbose: verbose,
),
......,
);
}
//二、步驟1中runner.run的第二個核心參數方法定義
//FlutterCommand爲packages/flutter_tools/lib/src/runner/flutter_command.dart中定義的抽象類
//這個方法本質就是把flutter執行的命令參數列表所有加入列表,相似命令模式
List<FlutterCommand> generateCommands({
@required bool verboseHelp,
@required bool verbose,
}) => <FlutterCommand>[
AnalyzeCommand(
......
),
AssembleCommand(verboseHelp: verboseHelp, buildSystem: globals.buildSystem),
AttachCommand(verboseHelp: verboseHelp),
BuildCommand(verboseHelp: verboseHelp),
ChannelCommand(verboseHelp: verboseHelp),
CleanCommand(verbose: verbose),
ConfigCommand(verboseHelp: verboseHelp),
CreateCommand(verboseHelp: verboseHelp),
DaemonCommand(hidden: !verboseHelp),
DevicesCommand(verboseHelp: verboseHelp),
DoctorCommand(verbose: verbose),
DowngradeCommand(verboseHelp: verboseHelp),
DriveCommand(verboseHelp: verboseHelp,
......
),
EmulatorsCommand(),
FormatCommand(),
GenerateCommand(),
GenerateLocalizationsCommand(
......
),
InstallCommand(),
LogsCommand(),
MakeHostAppEditableCommand(),
PackagesCommand(),
PrecacheCommand(
......
),
RunCommand(verboseHelp: verboseHelp),
ScreenshotCommand(),
ShellCompletionCommand(),
TestCommand(verboseHelp: verboseHelp),
UpgradeCommand(verboseHelp: verboseHelp),
SymbolizeCommand(
......
),
// Development-only commands. These are always hidden,
IdeConfigCommand(),
UpdatePackagesCommand(),
];
......
複製代碼
讓咱們把目光先移動到runner.dart
文件的 run 方法,而後回過頭來看上面代碼中的步驟1如何調用步驟2,以下:app
Future<int> run(
List<String> args,
List<FlutterCommand> Function() commands, {
bool muteCommandLogging = false,
bool verbose = false,
bool verboseHelp = false,
bool reportCrashes,
String flutterVersion,
Map<Type, Generator> overrides,
}) async {
......
//一、FlutterCommandRunner位於packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
return runInContext<int>(() async {
reportCrashes ??= !await globals.isRunningOnBot;
//二、建立runner對象實例,並把上一片斷代碼中步驟2方法返回的FlutterCommand列表追加進runner中
final FlutterCommandRunner runner = FlutterCommandRunner(verboseHelp: verboseHelp);
commands().forEach(runner.addCommand);
......
return runZoned<Future<int>>(() async {
try {
//三、依據args參數執行runner實例的run方法
await runner.run(args);
......
} catch (error, stackTrace) { // ignore: avoid_catches_without_on_clauses
......
}
}, onError: (Object error, StackTrace stackTrace) async { // ignore: deprecated_member_use
......
});
}, overrides: overrides);
}
複製代碼
能夠看到,首先實例化了一個 FlutterCommandRunner 對象,接着把全部支持的 FlutterCommand 列表加入 runner 對象中,而後調用了 runner 的 run 方法,因此咱們如今查看packages/flutter_tools/lib/src/runner/flutter_command_runner.dart
文件的 run 方法,以下:async
......
@override
Future<void> run(Iterable<String> args) {
......
//本質調用了父類CommandRunner的run方法,run方法調用了子類FlutterCommandRunner的runCommand方法
//子類FlutterCommandRunner的runCommand最終又調用了父類CommandRunner的runCommand方法
return super.run(args);
}
......
複製代碼
因此咱們接下來看父類 CommandRunner 的 runCommand 方法,以下:ide
Future<T?> runCommand(ArgResults topLevelResults) async {
//一、flutter命令後面傳遞進來參數,譬如build apk
var argResults = topLevelResults;
//二、前面分析過的,runner中添加的支持命令列表
var commands = _commands;
//三、定義一個Command變量,用來最終依據參數賦值爲對應的Command對象實例
Command? command;
var commandString = executableName;
//四、while條件爲真,由於commands爲支持的參數列表
while (commands.isNotEmpty) {
......
//五、填充指令
argResults = argResults.command!;
command = commands[argResults.name]!;
command._globalResults = topLevelResults;
command._argResults = argResults;
commands = command._subcommands as Map<String, Command<T>>;
commandString += ' ${argResults.name}';
......
}
......
//六、執行對應命令的run方法
return (await command.run()) as T?;
}
......
}
複製代碼
能夠看到,這就是一個標準的命令模式設計,先把支持的命令添加到列表,而後依據參數遍歷匹配對應命令進行執行。下面咱們以flutter build apk
命令爲例來看其對應的 BuildCommand 命令(packages/flutter_tools/lib/src/commands/build.dart
)實現,以下:工具
class BuildCommand extends FlutterCommand {
BuildCommand({ bool verboseHelp = false }) {
addSubcommand(BuildAarCommand(verboseHelp: verboseHelp));
addSubcommand(BuildApkCommand(verboseHelp: verboseHelp));
addSubcommand(BuildAppBundleCommand(verboseHelp: verboseHelp));
addSubcommand(BuildIOSCommand(verboseHelp: verboseHelp));
addSubcommand(BuildIOSFrameworkCommand(
buildSystem: globals.buildSystem,
verboseHelp: verboseHelp,
));
addSubcommand(BuildIOSArchiveCommand(verboseHelp: verboseHelp));
addSubcommand(BuildBundleCommand(verboseHelp: verboseHelp));
addSubcommand(BuildWebCommand(verboseHelp: verboseHelp));
addSubcommand(BuildMacosCommand(verboseHelp: verboseHelp));
addSubcommand(BuildLinuxCommand(
operatingSystemUtils: globals.os,
verboseHelp: verboseHelp
));
addSubcommand(BuildWindowsCommand(verboseHelp: verboseHelp));
addSubcommand(BuildWindowsUwpCommand(verboseHelp: verboseHelp));
addSubcommand(BuildFuchsiaCommand(verboseHelp: verboseHelp));
}
//上一小段代碼中command = commands[argResults.name]就是這麼獲得的
//name=build就是執行flutter build apk中的build字符串
@override
final String name = 'build';
@override
final String description = 'Build an executable app or install bundle.';
@override
Future<FlutterCommandResult> runCommand() async => null;
}
複製代碼
能夠看到,任意一個命令基本都繼承自 FlutterCommand 實現,命令的執行都是調用了 FlutterCommand 的 run 方法,以下:
abstract class FlutterCommand extends Command<void> {
......
//runner對象中最終執行調用的方法是這個
@override
Future<void> run() {
......
return context.run<void>(
name: 'command',
overrides: <Type, Generator>{FlutterCommand: () => this},
body: () async {
......
try {
//見名知意,先校驗再運行命令
commandResult = await verifyThenRunCommand(commandPath);
} finally {
......
}
},
);
}
......
@mustCallSuper
Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) async {
//一、若是須要更新緩存就先更新緩存
if (shouldUpdateCache) {
await globals.cache.updateAll(<DevelopmentArtifact>{DevelopmentArtifact.universal});
await globals.cache.updateAll(await requiredArtifacts);
}
globals.cache.releaseLock();
//二、校驗命令
await validateCommand();
//三、若是須要先執行pub就先執行,譬如pub get下載依賴
if (shouldRunPub) {
......
//四、執行pub get下載依賴,即下載pubspec.yaml裏配置的依賴
await pub.get(
context: PubContext.getVerifyContext(name),
generateSyntheticPackage: project.manifest.generateSyntheticPackage,
checkUpToDate: cachePubGet,
);
await project.regeneratePlatformSpecificTooling();
if (reportNullSafety) {
await _sendNullSafetyAnalyticsEvents(project);
}
}
setupApplicationPackages();
......
//五、真正開始執行命令
return runCommand();
}
}
複製代碼
繞一圈最終咱們又回到 BuildCommand 類,能夠發現其 runCommand 方法重寫爲空實現,而其構造時經過 addSubcommand 方法追加了不少子命令,譬如執行flutter build aar
編譯 aar 的 BuildAarCommand 命令、執行flutter build apk
編譯 apk 的 BuildApkCommand 命令。整個 sub command 與其宿主又算是一個責任鏈,因此上面一樣的套路順序對於 sub command 一樣適用,所以咱們去看下編譯 apk 產物的 BuildApkCommand 源碼(packages/flutter_tools/lib/src/commands/build_apk.dart
),以下:
class BuildApkCommand extends BuildSubCommand {
BuildApkCommand({bool verboseHelp = false}) {
......
//一堆參數的確認
}
//對應flutter build apk裏面子命令字符串apk
@override
final String name = 'apk';
......
//本質命令執行方法
@override
Future<FlutterCommandResult> runCommand() async {
......
//調用androidBuilder的buildApk方法進行真正的編譯,目測裏面的產物也就是上一篇文章分析的那些
//androidBuilder位於packages/flutter_tools/lib/src/android/android_builder.dart
await androidBuilder.buildApk(
project: FlutterProject.current(),
target: targetFile,
androidBuildInfo: androidBuildInfo,
);
return FlutterCommandResult.success();
}
}
複製代碼
順着這條路咱們繼續跟進位於packages/flutter_tools/lib/src/android/android_builder.dart
的 androidBuilder 屬性的 buildApk 方法,以下:
//本質是packages/flutter_tools/lib/src/context_runner.dart中context.run方法中的AndroidGradleBuilder實例
AndroidBuilder get androidBuilder {
return context.get<AndroidBuilder>();
}
//抽象類定義,AndroidBuilder
abstract class AndroidBuilder {
const AndroidBuilder();
// 定義編譯aar的方法
Future<void> buildAar({
@required FlutterProject project,
@required Set<AndroidBuildInfo> androidBuildInfo,
@required String target,
@required String outputDirectoryPath,
@required String buildNumber,
});
// 定義編譯apk的方法
Future<void> buildApk({
@required FlutterProject project,
@required AndroidBuildInfo androidBuildInfo,
@required String target,
});
// 定義編譯aab的方法
Future<void> buildAab({
@required FlutterProject project,
@required AndroidBuildInfo androidBuildInfo,
@required String target,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
});
}
複製代碼
因此咱們繼續去看 AndroidGradleBuilder 實現類(packages/flutter_tools/lib/src/android/gradle.dart
)的 buildApk 方法,以下:
class AndroidGradleBuilder implements AndroidBuilder {
AndroidGradleBuilder({
......
}) : ......;
......
//一、編譯 apk 的方法
@override
Future<void> buildApk({
@required FlutterProject project,
@required AndroidBuildInfo androidBuildInfo,
@required String target,
}) async {
//二、調用
await buildGradleApp(
project: project,
androidBuildInfo: androidBuildInfo,
target: target,
isBuildingBundle: false,
localGradleErrors: gradleErrors,
);
}
......
//三、真的編譯
Future<void> buildGradleApp({
@required FlutterProject project, //FlutterProject.current()
@required AndroidBuildInfo androidBuildInfo, //build configuration
@required String target, //dart代碼入口,缺省lib/main.dart
@required bool isBuildingBundle, //是aab仍是apk,默認false則apk
@required List<GradleHandledError> localGradleErrors,
bool shouldBuildPluginAsAar = false, //是否是將插件編譯爲aar
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
int retries = 1,
}) async {
//四、檢查支持的android版本,獲取android編譯產物目錄,即gradle中配置的build產物目錄,默認爲項目根目錄下的build目錄
if (!project.android.isSupportedVersion) {
_exitWithUnsupportedProjectMessage(_usage, _logger.terminal);
}
final Directory buildDirectory = project.android.buildDirectory;
//五、讀取安卓相關屬性文件判斷是否使用androidx,而後發送編譯事件參數
final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot);
if (usesAndroidX) {
BuildEvent('app-using-android-x', flutterUsage: _usage).send();
} else if (!usesAndroidX) {
BuildEvent('app-not-using-android-x', flutterUsage: _usage).send();
......
}
//六、更新安卓項目中local.properties中的versionName和versionCode值,值來自於public.yaml文件配置
updateLocalProperties(project: project, buildInfo: androidBuildInfo.buildInfo);
//七、編譯aar的話就走buildPluginsAsAar方法進行
if (shouldBuildPluginAsAar) {
// Create a settings.gradle that doesn't import the plugins as subprojects.
createSettingsAarGradle(project.android.hostAppGradleRoot, _logger);
await buildPluginsAsAar(
project,
androidBuildInfo,
buildDirectory: buildDirectory.childDirectory('app'),
);
}
//八、獲取編譯apk或者aab對應的標準安卓task name,構建參數等信息,也就是gradle命令後面一堆的參數構造
final BuildInfo buildInfo = androidBuildInfo.buildInfo;
final String assembleTask = isBuildingBundle
? getBundleTaskFor(buildInfo)
: getAssembleTaskFor(buildInfo);
......
final List<String> command = <String>[
_gradleUtils.getExecutable(project),
];
......
//九、依據條件追加command的一堆參數,譬如-Psplit-per-abi=true、-Pverbose=true、--no-daemon等
......
try {
exitCode = await _processUtils.stream(
command,
workingDirectory: project.android.hostAppGradleRoot.path,
allowReentrantFlutter: true,
environment: <String, String>{ if (javaPath != null) 'JAVA_HOME': javaPath, }, mapFunction: consumeLog, ); } on ProcessException catch (exception) { ...... } finally { status.stop(); } ...... } ...... } 複製代碼
哈哈,真相了,這下配合《Flutter Android 工程結構及應用層編譯源碼深刻分析》一文首尾呼應後你應該完全明白 Flutter android apk 是怎麼編譯的流程!
如今咱們結合《Flutter Android 工程結構及應用層編譯源碼深刻分析》和這篇進行關聯總結,能夠總結出執行flutter build apk
命令背後的大體主流程以下: 既然執行flutter build apk
命令你都搞明白了,那麼其餘 flutter 相關的任何命令你是否也能夠本身觸類旁通進行分析學習,本質都同樣哈。因爲我這裏時間有限,因此對於flutter pub get
、flutter doctor
等其餘命令再也不作詳細分析。