androidflutterkotlin

How to load Flutter assets in Android


I am trying to load some audio files that are part of my Flutter assets into Android, however I can't seem to find the correct approach to do so, and with the reccomended way having been deprecated (use of PluginRegistry.Regitry based APIs).

This is my file hierarchy:

project
├─audio
│ └─file.wav
├─pubspec.yml
└─...

This is my pubspec.yml:

flutter:
  assets:
    - audio/file.wav
  ...
...

This is my MainActivity.kt:

class MainActivity : FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        
        // Where I'd like to load my audio file

        ...
    }
}

I have attempted a few implementations, including usage of FluterLoader and FlutterInjector, however I also seem to need access to an instance of the AssetManager that Flutter is using. Unlike the deprecated examples mentioned above, it doesn't seem like the FlutterEngine gives direct access to it's AssetManager as it is private under FlutterEnginer.dartExecutor.binaryMessenger.assetManager.

I'm unsure whether my previous approaches are in the correct/intended direction, so I'm curious as to how to load my Flutter audio files into Android correctly?

I am currently running on Flutter 3.24.4

Thank you in advance!


Solution

  • Looks like the AssetManager is directly available simply by using assets! For example:

    class MainActivity : FlutterActivity() {
        override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
            super.configureFlutterEngine(flutterEngine)
            
            val assetManager: AssetManager = assets
    
            ...
        }
    }