gpt4 book ai didi

android - 如何将方法 channel 添加到 Flutter Fragment

转载 作者:行者123 更新时间:2023-12-03 03:15:32 24 4
gpt4 key购买 nike

自从我将 Flutter SDK 升级到 1.12.13+hotfix.8 后, fragment 中较旧的 FlutterView 实现不再有效,因为 Facade (Flutter) 库现在已弃用。

Flutter.createView(activity!!, lifecycle, mRoute)

根据官方文档,我们可以添加如下所示的 FlutterFragment -

FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
.initialRoute("myInitialRoute/")
.build();

但找不到如何在扩展 Flutter fragment 的自定义 Flutter fragment 中添加方法 channel 。

最佳答案

这就是我将 flutter 引擎与 flutter fragment 连接的方式,它运行得非常好。如果你使用缓存的引擎和 fragment ,即使你重新打开它,屏幕也会保持状态。如果您不想保存 fragment 状态,请避免缓存。

package com.test.app

import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.plugin.common.MethodChannel

class SampleActivity: AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)

initFlutterEngine()
attachFlutterFragment()
}

private fun initFlutterEngine(): FlutterEngine {
var flutterEngine = FlutterEngineCache.getInstance().get(ENGINE_ID)

if (null == flutterEngine) {
flutterEngine = FlutterEngine(this)
flutterEngine.navigationChannel.setInitialRoute("/")
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
FlutterEngineCache
.getInstance()
.put(ENGINE_ID, flutterEngine)
setMethodChannels(flutterEngine)
}
return flutterEngine
}

private attachFlutterFragment() {
var flutterFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as FlutterFragment?
if (null == flutterFragment) {
flutterFragment =
FlutterFragment.withCachedEngine(ENGINE_ID)
.shouldAttachEngineToActivity(true)
.build() as FlutterFragment
}

supportFragmentManager
.beginTransaction()
.add(R.id.flutter_fragment_container,
flutterFragment,
FRAGMENT_TAG
)
.commit()
}

private fun setMethodChannels(flutterEngine: FlutterEngine) {
MethodChannel(flutterEngine.dartExecutor, FLUTTER_CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
DUMMY_METHOD -> {
val params = HashMap<String, String>()

result.success(params)
}
else -> result.notImplemented()
}
}
}
}

关于android - 如何将方法 channel 添加到 Flutter Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60228290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com