从 Flutter 上的调试构建中排除资产

Dan*_*iel 6 assets gradle android-studio source-sets flutter

我的 /assets/files 文件夹中有 8000 多个名为(1.txt、2.txt、3.txt 等)的文件。但是,我的调试版本不需要所有这些。我只需要其中的前 30 个。事实上,如果我将所有这些文件留在资产文件夹中,构建时间会很长。

我了解到有一个源集概念,但它仅适用于 Android Studio 上的 Java 和 Kotlin。

如何从 Flutter 的调试版本中排除那些超出的文件?

FDu*_*hen 2

This 'problem' don't have any built-in solution yet (because of Dart and Flutter's design)

It was discussed on the following issue :
https://github.com/flutter/flutter/issues/79261

A bit hacky (but working) solution is to script the edition of your pubspec.yaml to update the assets to import before each build.
Since there is no 'pre-build' method yet with the Flutter Framework, you can use a Makefile to execute your script.

The following would work :

Step 1 - Update your pubspec.yaml to 'tag' the part of your assets you want to update.

flutter:
  assets:
    - assets/icons/icon.png
    - assets/translations/
    #DYN_ASSETS_START 
    - assets/images/
    #DYN_ASSETS_END
Run Code Online (Sandbox Code Playgroud)

The tags here are obviously #DYN_ASSETS_START and #DYN_ASSETS_END

Step 2 - Create a Script to update your assets.
The following is just a working example, it can be strongly improved since I'm far away from being an expert in Bash.
The point of the script is to find the two tags which were set in your pubspec.yaml and update everything which is between those two tags.

#!/bin/bash

BUILD_MODE=$1
nl='
'

if [ "$BUILD_MODE" = "DEBUG" ]; then
    sed '/#DYN_ASSETS_START/,/#DYN_ASSETS_END/c\ 
    #DYN_ASSETS_START'"\\${nl}"'    - assets/images/image1.png'"\\${nl}"'    - assets/images/image2.png'"\\${nl}"'    - assets/images/image3.png'"\\${nl}"'    - assets/images/image4.png'"\\${nl}"'    - assets/images/image5.png'"\\${nl}"'    #DYN_ASSETS_END'"\\${nl}" pubspec.yaml > temp.yaml
    mv temp.yaml pubspec.yaml
elif [ "$BUILD_MODE" = "RELEASE" ]; then
    sed '/#DYN_ASSETS_START/,/#DYN_ASSETS_END/c\ 
    #DYN_ASSETS_START'"\\${nl}"'    - assets/images/'"\\${nl}"'    #DYN_ASSETS_END'"\\${nl}" pubspec.yaml > temp.yaml
    mv temp.yaml pubspec.yaml
fi
Run Code Online (Sandbox Code Playgroud)

Disclaimer : this script is not sexy at all.
sed may not be the best tool to achieve this, the code is hard to maintain read and evolve, and I only tested it on MacOS (I doubt it'd work on another environment).
The goal of this script here is to give you an idea of a workaround fulfilling the author's request.

Step 4 - Create a Makefile.

build-android-debug:
    ./your_script.sh DEBUG
    flutter pub get
    flutter build apk

build-android-release:
    ./your_script.sh RELEASE
    flutter pub get
    flutter build apk --release
Run Code Online (Sandbox Code Playgroud)

Step 5 - Trigger the Makefile Flow

make build-android-debug
Run Code Online (Sandbox Code Playgroud)