Flutter Plugin - cannot resolve method 'startActivityForResult'

Viewed 328

Recently I am working on a Flutter plugin for my project. My plugin requires startActivityForResult but can't figure out how to use it according to Flutter plugin development. I have given my code below.

public class MyPlugin implements FlutterPlugin, MethodCallHandler {

    private static final int REQUEST_CODE = 1;
    Result result;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "my_plugin");
        channel.setMethodCallHandler(this);
    }
    
    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        this.result = result;
        if (call.method.equals("myMethod")) {
            myMethod();
        } else {
            result.notImplemented();
        }
    }


    private void myMethod() {
        // my intent instance will be here
        startActivityForResult(intent, REQUEST_CODE); // Cannot resolve method 'startActivityForResult'
    }



    @Override
    public boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        try {
            if (requestCode == REQUEST_CODE) {
                result.success("done");
            } else {
                result.error("Something went wrong", null, null);
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.toString());
        }

        return false;
    }

}
1 Answers

Try this solution to get the Context. After, call the intent using the Context:

private void myMethod() {
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
Related