如何解决通过setMethodCallHandler设置的Flutter方法调用处理程序未运行
我希望我的应用获取共享文本并以初始(主要)路线显示。它可以获取文本,但无法在路由中显示该文本,因为setMethodCallHandler
是在初始路由的initState中设置的;但channel方法在该处理程序集之前运行。我不知道该如何解决这个问题。
故事:
我在主要活动中添加了一个新的意图过滤器,以获取共享文本:
AndroidManifest.xml中的意图过滤器:
...
<intent-filter>
<action android:name="android.intent.action.PROCESS_TEXT" />
<data android:mimeType="text/plain"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
...
MainActivity.kt:
package com.example.myapp
import android.content.Intent
import android.os.Bundle
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
class MainActivity : FlutterActivity() {
companion object {
private const val CHANNEL = "share_text_channel"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val channel = MethodChannel(flutterEngine?.getDartExecutor(),CHANNEL)
if (intent.action == Intent.ACTION_PROCESS_TEXT) {
val sharedText = intent.getStringExtra(Intent.EXTRA_PROCESS_TEXT)
channel.invokeMethod("getSharedText",sharedText)
println(sharedText) // <--- this does work and shows the shared text
}
}
}
上面的行println(sharedText)
正确地输出了共享文本,因此看起来似乎正常。
我的初始路线的状态:
_ScreenHomeState() {
_channel.setMethodCallHandler(_handleMethod);
}
static const MethodChannel _channel =
const MethodChannel('share_text_channel');
String _sharedText = '';
Future<dynamic> _handleMethod(MethodCall call) async {
print('run?'); // <-- doesn't run
switch (call.method) {
case "getSharedText":
setState(() {
_sharedText = call.arguments.toString();
});
return call.arguments;
}
}
因此,该意图有效,活动可以读取共享文本并将其输出。但是我的初始路线无法到达此文字。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。