Flatter Android现有主机应用程序扩展了Fragment/AppCompatActivity,点击按钮需要向Flatter Dart发送消息
我有一个现有的Android应用程序,并通过以下步骤将颤振模块作为库添加到其中 我有一个已经存在的片段,它扩展了片段,并希望使用通道从这个片段向Dart发送消息。 为此,请遵循以下步骤: 单击一个按钮,将此代码添加到我现有的片段中,我得到的错误是“无法解析方法getflatterview()”Flatter Android现有主机应用程序扩展了Fragment/AppCompatActivity,点击按钮需要向Flatter Dart发送消息,android,flutter,flutter-dependencies,Android,Flutter,Flutter Dependencies,我有一个现有的Android应用程序,并通过以下步骤将颤振模块作为库添加到其中 我有一个已经存在的片段,它扩展了片段,并希望使用通道从这个片段向Dart发送消息。 为此,请遵循以下步骤: 单击一个按钮,将此代码添加到我现有的片段中,我得到的错误是“无法解析方法getflatterview()” 问题在于颤振中的范围AppCompatActivity,您需要使用颤振活动对其进行扩展,在其工作后,下面是代码 public class MainActivity extends FlutterActiv
问题在于颤振中的范围AppCompatActivity,您需要使用颤振活动对其进行扩展,在其工作后,下面是代码
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "flutter.native/helper";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this)
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("helloFromNativeCode")) {
String greetings = helloFromNativeCode();
result.success(greetings);
}
}
});
}
}
最终可以通过添加虚拟视图来修复它
View flutterView = Flutter.createView(
MainActivity.this,
getLifecycle(),
"anyText"
);
new MethodChannel((BinaryMessenger) flutterView, CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("helloFromNativeCode")) {
String greetings = helloFromNativeCode();
result.success(greetings);
}
}
});
我的现有代码已使用AppCompatActivity编写,因此无法更改为FlatterActivity。但GetFlatterView()方法仅在FlatterActivity中可用。您可以更改它并尝试一次
View flutterView = Flutter.createView(
MainActivity.this,
getLifecycle(),
"anyText"
);
new MethodChannel((BinaryMessenger) flutterView, CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("helloFromNativeCode")) {
String greetings = helloFromNativeCode();
result.success(greetings);
}
}
});