androidflutterflutter-channel

create method channel after upgrading flutter- can not resolve method getFlutterView()


i was using native android method in my flutter app using documentation which said use

MethodChannel(flutterView, CHANNEL).setMethodCallHandler...

but after upgrading flutter the MethodChannel function does not require flutterView and there is no flutterView anymore.

can not resolve method getFlutterView()

i think there should be a new tutorial for creating channel

instead it needs some BinaryMessenger which i don't know what to give instead.

this is the old code which is not working anymore:

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/battery";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodCallHandler() {
                @Override
                public void onMethodCall(MethodCall call, Result result) {
                    // Note: this method is invoked on the main thread.
                    // TODO
                }
            });
}

Solution

  • Replace getFlutterView() with getFlutterEngine().getDartExecutor().getBinaryMessenger().

    You don't actually need the .getBinaryMessenger() as DartExecutor implements BinaryMessenger itself (by just forwarding), but I think it's more correct to specify the messenger.