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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With