0

I am trying to open FlutterActivity in my existing android application. Before I was creating new flutter engine every time I was opening activity like this:

FlutterActivity
   .withNewEngine()
   .build(context)

And everything was working fine besides a little lag while opening the activity. To get rid of the lag I wanted to switch to using cached engine. I followed this official tutorial: LINK And ended up with smething like this:

In my Application class:

class App : Application() {

    lateinit var flutterEngine: FlutterEngine

    override fun onCreate() {
        ...

        flutterEngine = FlutterEngine(this)
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )

        FlutterEngineCache
            .getInstance()
            .put("myEngineId", flutterEngine)
    }
}

And later in my application on the button click, in the same place that I was successfully opening FlutterActivity:

FlutterActivity
   .withCachedEngine("myEngineId")
   .build(context)

So I basically followed the all the instructions but the effect that I get now is after the button click there is even longer lag than before and then there is only black screen being displayed. My flutter screen is not displayed and application is kind of frozen I can't go back or do anything. There is also no error or any useful info in the logs. I have no idea what is going on. What am I doing wrong?

matip
  • 794
  • 3
  • 7
  • 27

1 Answers1

0

To Use cached FlutterEngine In FlutterActivity you must declare provideFlutterEngine method.

class DemoActivity : FlutterActivity() {

override fun provideFlutterEngine(context: Context): FlutterEngine? =
    FlutterEngineCache.getInstance().get(FlutterConstants.ENGINE_ID)

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "demo-channel")
        .setMethodCallHandler { call, result ->
            if (call.method == "demo-method") {
                demoMethod()
                result.success(null)
            } else {
                result.notImplemented()
            }
        }
}

private fun demoMethod() {
    // Do native code
}

}
  • Do I really have to create my own implementation of `FlutterActivity`? Can I just the base one? In the tutorial I provided there is no info about that – matip Oct 28 '22 at 09:06
  • @matip You can check https://github.com/flutter/flutter/wiki/Experimental:-Reuse-FlutterEngine-across-screens – Shreya Patel Oct 28 '22 at 09:27
  • It does not work. I still get black screen while using cashed engine – matip Oct 28 '22 at 10:55