Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assets do not load on Android add-to-app flutter_module: Unable to load asset: "AssetManifest.json" #120870

Closed
PhillDubois opened this issue Feb 16, 2023 · 13 comments
Assignees
Labels
a: assets Packaging, accessing, or using assets a: existing-apps Integration with existing apps via the add-to-app flow c: crash Stack traces logged to the console engine flutter/engine repository. See also e: labels. found in release: 3.7 Found to occur in 3.7 has reproducible steps The issue has been confirmed reproducible and is ready to work on P3 Issues that are less important to the Flutter project platform-android Android applications specifically team-android Owned by Android platform team triaged-android Triaged by Android platform team

Comments

@PhillDubois
Copy link

Steps to Reproduce

  1. Clone the repository: https://github.com/PhillDubois/flutter_add_2_app
  2. inside flutter_module run flutter pub get
  3. run the android app
  4. Tap the "Open flutter activity" button

Expected results:
I expect to see the icons and image loaded.

Actual results:
Neither the icons nor the image loads.

image

Code sample

on the flutter_module folder I added:

assets/flutter_dash.jpeg

on main.dart

import 'package:flutter/material.dart';
import 'package:ionicons/ionicons.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(
    const App(),
  );
}

class App extends StatelessWidget {
  const App({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            Image.asset('assets/flutter_dash.jpeg'),
            Icon(Icons.add),
            Icon(Ionicons.add),
          ],
        ),
      ),
    );
  }
}

And my pubspect.yaml file is like

name: flutter_module
description: A new Flutter module project.

version: 1.0.0+1

environment:
  sdk: ">=2.18.0 <3.0.0"

dependencies:
  # Icons
  ionicons: ^0.2.2

  flutter:
    sdk: flutter

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^2.0.0
  build_runner:

flutter:
  uses-material-design: true
  # generate: true
  assets:
    - assets/

  module:
    androidX: true
    androidPackage: fr.cashbee.flutter_module
    iosBundleIdentifier: fr.cashbee.flutterModule

On Android I have the following code:

package com.example.myapplication.flutter

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import com.example.myapplication.R
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.android.RenderMode
import io.flutter.embedding.android.TransparencyMode
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.FlutterEngineGroup
import io.flutter.embedding.engine.dart.DartExecutor

class CBFlutterActivity: AppCompatActivity()
{
    companion object
    {
        private const val FLUTTER_FRAGMENT_TAG = "flutter_page_fragment"
    }

    private var flutterFragment: FlutterFragment? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        val root = FlutterEngineHandler.createRootView(this)
        setContentView(root)

        flutterFragment = FlutterEngineHandler.attachFlutterFragment(this, root, supportFragmentManager, FLUTTER_FRAGMENT_TAG, FlutterEngineEntrypoint.Main)

    }

    override fun onNewIntent(intent: Intent?)
    {
        if (intent != null)
        {
            flutterFragment?.onNewIntent(intent)
        }
        super.onNewIntent(intent)
    }

    override fun onBackPressed()
    {
        super.onBackPressed()
        flutterFragment?.onBackPressed()
    }

    override fun onUserLeaveHint()
    {
        super.onUserLeaveHint()
        flutterFragment?.onUserLeaveHint()
    }

    override fun onDestroy()
    {
        flutterFragment?.detachFromFlutterEngine()
        super.onDestroy()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    {
        flutterFragment?.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }

}

class FlutterEngineHandler
{
    companion object
    {

        private const val LOG_TAG = "FlutterEngineHandler"

        private lateinit var engineGroup: FlutterEngineGroup

        fun initialize(context: Context)
        {
            engineGroup = FlutterEngineGroup(context)
        }

        fun createOrGetEngine(
            context: Context,
            engineEntrypoint: FlutterEngineEntrypoint): FlutterEngine
        {
            var cachedEngine = getEngine(engineEntrypoint)
            if (cachedEngine == null)
            {
                Log.d(LOG_TAG, "Engine ${engineEntrypoint.engineId} does not exist, creating engine")

                val entrypoint = DartExecutor.DartEntrypoint(engineEntrypoint.pathToBundle, engineEntrypoint.entrypoint)
                cachedEngine = engineGroup.createAndRunEngine(context, entrypoint)
                FlutterEngineCache.getInstance().put(engineEntrypoint.engineId, cachedEngine)
            }
            return cachedEngine!!
        }

        fun getEngine(engineEntrypoint: FlutterEngineEntrypoint): FlutterEngine?
        {
            return FlutterEngineCache.getInstance().get(engineEntrypoint.engineId)
        }

        fun destroyEngine(engineEntrypoint: FlutterEngineEntrypoint)
        {
            getEngine(engineEntrypoint)?.let {
                FlutterEngineCache.getInstance().remove(engineEntrypoint.engineId)
                it.destroy()
                Log.d(LOG_TAG, "Destroyed engine ${engineEntrypoint.engineId}")
            }
        }

        fun createRootView(context: Context): ViewGroup
        {
            val view = LinearLayout(context)
            view.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            view.orientation = LinearLayout.VERTICAL
            return view
        }

        fun attachFlutterFragment(
            context: Context,
            root: ViewGroup,
            fragmentManager: FragmentManager,
            fragmentTag: String,
            engineEntrypoint: FlutterEngineEntrypoint,
        ): FlutterFragment
        {
            var flutterFragment = fragmentManager.findFragmentByTag(fragmentTag) as FlutterFragment?

            if (flutterFragment == null)
            {
                flutterFragment = FlutterFragment
                    .withCachedEngine(engineEntrypoint.engineId)
                    .shouldAttachEngineToActivity(true)
                    .renderMode(RenderMode.surface)
                    .transparencyMode(TransparencyMode.opaque)
                    .build()

                fragmentManager
                    .beginTransaction()
                    .add(R.id.flutter_fragment_id, flutterFragment, fragmentTag)
                    .commit()
            }

            val flutterContainer = FrameLayout(context)
            root.addView(flutterContainer)
            flutterContainer.id = R.id.flutter_fragment_id
            flutterContainer.layoutParams = LinearLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT,
                1.0f)

            return flutterFragment
        }
    }
}


enum class FlutterEngineEntrypoint(
    val engineId: String,
    val entrypoint: String,
    val pathToBundle: String = "lib/main.dart")
{
    Main("MAIN", "main"),
}

and

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        FlutterEngineHandler.initialize(applicationContext)
        FlutterEngineHandler.createOrGetEngine(applicationContext, FlutterEngineEntrypoint.Main)
    }
}
Logs

Logs:

E/flutter: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: "AssetManifest.json".
    The asset does not exist or has empty data.
    #0      PlatformAssetBundle.load.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:254:9)
    <asynchronous suspension>
    #1      AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:83:27)
    <asynchronous suspension>

flutter analyze


Analyzing flutter_module...                                       
No issues found! (ran in 1.1s)

flutter doctor -v


[✓] Flutter (Channel stable, 3.7.3, on macOS 13.0 22A380
    darwin-arm64, locale en-FR)
    • Flutter version 3.7.3 on channel stable at
      /Users/philippedubois/Sdks/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 9944297138 (7 days ago), 2023-02-08
      15:46:04 -0800
    • Engine revision 248290d6d5
    • Dart version 2.19.2
    • DevTools version 2.20.1

[✓] Android toolchain - develop for Android devices (Android SDK
    version 33.0.1)
    • Android SDK at /Users/philippedubois/Library/Android/sdk
    • Platform android-33, build-tools 33.0.1
    • Java binary at:
      /Users/philippedubois/Library/Java/JavaVirtualMachines/corre
      tto-17.0.5/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment Corretto-17.0.5.8.1
      (build 17.0.5+8-LTS)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14C18
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google
      Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio (version 2022.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] VS Code (version 1.75.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.58.0

[✓] Connected device (3 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64
      • Android 13 (API 33) (emulator)
    • macOS (desktop)             • macos         • darwin-arm64
      • macOS 13.0 22A380 darwin-arm64
    • Chrome (web)                • chrome        • web-javascript
      • Google Chrome 109.0.5414.119

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.
@huycozy huycozy added the in triage Presently being triaged by the triage team label Feb 16, 2023
@huycozy
Copy link
Member

huycozy commented Feb 16, 2023

@PhillDubois thanks for filing the issue. This issue is reproducible with provided sample code.

When replacing with a network image on Flutter module, it can be displayed well.

Asset image ❌ Network image ✅

✅: No Issue ❌: Issue reproduced

flutter doctor -v (stable and master)
[✓] Flutter (Channel stable, 3.7.3, on macOS 13.0.1 22A400 darwin-x64, locale en-VN)
    • Flutter version 3.7.3 on channel stable at /Users/huynq/Documents/GitHub/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 9944297138 (17 hours ago), 2023-02-08 15:46:04 -0800
    • Engine revision 248290d6d5
    • Dart version 2.19.2
    • DevTools version 2.20.1

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/huynq/Library/Android/sdk
    • Platform android-33, build-tools 31.0.0
    • ANDROID_HOME = /Users/huynq/Library/Android/sdk
    • Java binary at: /Users/huynq/Library/Java/JavaVirtualMachines/corretto-1.8.0_302/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment Corretto-8.302.08.1 (build 1.8.0_302-b08)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[!] Android Studio (version 2022.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    ✗ Unable to find bundled Java version.
    • Try updating or re-installing Android Studio.

[✓] IntelliJ IDEA Community Edition (version 2022.1.1)
    • IntelliJ at /Users/huynq/Library/Application Support/JetBrains/Toolbox/apps/IDEA-C/ch-0/221.5591.52/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.75.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.58.0

[✓] Connected device (3 available)
    • SM T225 (mobile) • R9JT3004VRJ • android-arm64  • Android 13 (API 33)
    • macOS (desktop)  • macos       • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
    • Chrome (web)     • chrome      • web-javascript • Google Chrome 110.0.5481.77

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.
[!] Flutter (Channel master, 3.8.0-13.0.pre.51, on macOS 13.0.1 22A400 darwin-x64, locale en-VN)
    • Flutter version 3.8.0-13.0.pre.51 on channel master at /Users/huynq/Documents/GitHub/flutter_master
    ! Warning: `flutter` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
    ! Warning: `dart` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/dart, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision efde350812 (15 minutes ago), 2023-02-15 21:49:06 -0500
    • Engine revision a966cf878f
    • Dart version 3.0.0 (build 3.0.0-240.0.dev)
    • DevTools version 2.21.1
    • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/huynq/Library/Android/sdk
    • Platform android-33, build-tools 31.0.0
    • ANDROID_HOME = /Users/huynq/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)

[✓] IntelliJ IDEA Community Edition (version 2022.1.1)
    • IntelliJ at /Users/huynq/Library/Application Support/JetBrains/Toolbox/apps/IDEA-C/ch-0/221.5591.52/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.75.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.58.0

[✓] Connected device (2 available)
    • macOS (desktop) • macos  • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 110.0.5481.100

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.

@huycozy huycozy added c: crash Stack traces logged to the console platform-android Android applications specifically a: assets Packaging, accessing, or using assets a: existing-apps Integration with existing apps via the add-to-app flow has reproducible steps The issue has been confirmed reproducible and is ready to work on found in release: 3.7 Found to occur in 3.7 engine flutter/engine repository. See also e: labels. and removed in triage Presently being triaged by the triage team labels Feb 16, 2023
@camsim99 camsim99 added the P3 Issues that are less important to the Flutter project label Feb 16, 2023
@PhillDubois
Copy link
Author

I don't know it that can help, but on the android project folder when I do the command:
ls app/build/intermediates/assets/localDebug/mergeLocalDebugAssets/flutter_assets/

I have the following results:

AssetManifest.json    NOTICES.Z             fonts                 kernel_blob.bin       shaders
FontManifest.json     assets                isolate_snapshot_data packages              vm_snapshot_data

So the assets are there, I think that flutter is just not being able to read on the correct directory.

@BenevidesLecontes
Copy link

We're having the same issue and it's blocking us for using flutter (modules, plugins and libs) in our company.

@PhillDubois
Copy link
Author

The workaround for the moment is to fetch everything and cache, including the fonts.

@korilin
Copy link

korilin commented Jun 29, 2023

Are there any temporary solutions for the business code?
After we upgraded flutter 3.7.12, we found that similar errors were reported online Android users.

FlutterError: Unable to load asset: "AssetManifest.json".

#0 PlatformAssetBundle.load.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:254)
#1 _rootRunUnary (dart:async/zone.dart:1406)
<asynchronous suspension>
#2 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:83)
<asynchronous suspension>

The error was reported from the user and I was unable to reproduce the problem myself in our project myself.

In addition, I found that the error was followed by a line of type error message in the log.I don't know if it's relevant.

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'Null' is not a subtype of type 'bool'

@flutter-triage-bot flutter-triage-bot bot added multiteam-retriage-candidate team-android Owned by Android platform team triaged-android Triaged by Android platform team labels Jul 8, 2023
@PhillDubois
Copy link
Author

@korilin as I've mentioned, the workaround I've found is fetching and caching everything, for fonts, you can use FontLoader to load them, otherwise, I haven't found a better solution.

@SanginiG
Copy link

Image.asset(assetName,
package: 'package_name', height: height, width: width, fit: fit); using the package name works, defined in the pubspec.yaml of your module_project

@PhillDubois
Copy link
Author

  1. https://github.com/PhillDubois/flutter_add_2_app

have you tried with the code here https://github.com/PhillDubois/flutter_add_2_app ?

because it still doesn't work for me

@gmackall
Copy link
Member

Debugging this at the moment, dumping some thoughts for now

Unzipping the resultant apk in both the good (flutter run in the module) and bad (running the android app, depending on the module as source) cases - the assets are in the APK.

Potentially looks like this string is wrong in the case of add 2 app (specifically when depending on the module as source).

When running the good case, this string is flutter_assets/FontManifest.json, for example, when trying to load FontManifest.json, which lines up path within the assets directory in the apk.

But in the bad case (a2a depending on module source), the string is lib/main.dart/FontManifest.json, which doesn't line up with the assets directory in the apk.

@gmackall
Copy link
Member

gmackall commented May 1, 2024

Confirmed that I can force the assets to load properly in the a2a case by just manually replacing the directory string in question with a hardcoded lib/main.dart - so that is where we should be looking. Just need to find out why we aren't looking there in the first place.

@gmackall
Copy link
Member

gmackall commented May 2, 2024

Hmm, it looks like the reason your assets aren't loading in the example app is that you are specifying a path here
https://github.com/PhillDubois/flutter_add_2_app/blob/main/android/app/src/main/java/com/example/myapplication/flutter/FlutterEngineEntrypoint.kt#L6
And that configuration doesn't change where the assets get placed in the apk - just where we look for them. So if you changed it to the default ("flutter_assets", or FlutterInjector.instance().flutterLoader().findAppBundlePath()), they load properly.

Still need to figure out if that is WAI or if it should be changing both where we place and where we look for assets.

@gmackall
Copy link
Member

gmackall commented May 2, 2024

Given that this path that you are passing in could even be computed at runtime, I'm going to say this is WAI. The problem is just that you are passing lib/main.dart as the directory which contains the assets, which isn't correct. See my previous comment on how to fix

@gmackall gmackall closed this as completed May 2, 2024
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 16, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
a: assets Packaging, accessing, or using assets a: existing-apps Integration with existing apps via the add-to-app flow c: crash Stack traces logged to the console engine flutter/engine repository. See also e: labels. found in release: 3.7 Found to occur in 3.7 has reproducible steps The issue has been confirmed reproducible and is ready to work on P3 Issues that are less important to the Flutter project platform-android Android applications specifically team-android Owned by Android platform team triaged-android Triaged by Android platform team
Projects
None yet
Development

No branches or pull requests

8 participants