Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a FlutterActivity subclass using a cached engine

I'm currently adding a view developed using Flutter to an existing Android app. I have been following the tutorials found in the Flutter website and decided to used a cached engine in order to minimize the delay that users may experience when navigating to the Flutter portion of the app. In order to do so, you must launch your Flutter activity like

startActivity(
    FlutterActivity
      .withCachedEngine("my_engine_id")
      .build(this) // this is a Context

)

After a while I need to wirte a method channel to communicate from the Flutter portion of the app back to the Android host app, so I followed the instructions found in another of Flutter's tutorials, where it is shown that the activity that implements the channel must extend FlutterActivity.

So my problem is that I'm not sure how to initialize this activity using a cached engine, since I obviously can't use FlutterActivity.withCachedEngine anymore. Has anyone solved this already?

like image 790
Nicolás Carrasco-Stevenson Avatar asked Jun 10 '20 06:06

Nicolás Carrasco-Stevenson


1 Answers

After looking at FlutterActivity documentation I found the provideFlutterEngine method. The doc description clearly states that:

This hook is where a cached FlutterEngine should be provided, if a cached FlutterEngine is desired.

So the final implementation of my class looks like this now

class MyActivity : 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, "my-channel")
            .setMethodCallHandler { call, result ->
                if (call.method == "my-method") {
                    myMethod()
                    result.success(null)
                } else {
                    result.notImplemented()
                }
            }
    }

    private fun myMethod() {
        // Do native stuff
    }

}

And I simply start it writing startActivity(Intent(this, MyActivity::class.java))

like image 190
Nicolás Carrasco-Stevenson Avatar answered Oct 17 '22 20:10

Nicolás Carrasco-Stevenson