Flutter扩展了Fragment / AppCompatActivity的Android现有主机应用程序,只需单击按钮即可向Flutter Dart发送消息

时间:2019-06-23 05:02:28

标签: android flutter flutter-dependencies

我有一个现有的Android应用,并通过遵循此link向其中添加了flutter模块作为库。

我有一个现有的片段,该片段扩展了Fragment,并希望使用通道从该片段向Dart发送消息。 为此link之后:

在单击按钮后将此代码添加到我现有的Fragment中,我收到一个错误是“ 无法解析方法getFlutterView()

 public class MainActivity extends AppCompatActivity {
private static final String CHANNEL = "flutter.native/helper";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    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);
                    }
                }
            });

}
}

enter image description here

2 个答案:

答案 0 :(得分:0)

问题在于在应用范围内 AppCompatActivity ,您需要使用 FlutterActivity 对其进行扩展,然后才能进行扩展,下面是代码

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);
                    }
                }
            });

}
}

答案 1 :(得分:0)

最后可以通过添加虚拟FlutterView对其进行修复,

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);
                    }
                }
            });