FlutterActivity MethodChannel and FlutterView

the new embedding does not support the old flutterview.
flutteractivity tutorial
flutteractivity example
writing custom platform-specific code
attaching flutterengine to the activity that owns this fragment.
configureflutterengine
flutter activity
configureflutterengine not found

So I wrote a Flutter App about 4 Months ago. Now I wanted to do a small change, but I can't compile the app anymore, because GeneratedPluginRegistrant.registerWith(this) doesn't work anymore, I didn't change the Kotlin code only the Dart code.

The "this" in "GeneratedPluginRegistrant.registerWith(this)" shows me this error:

Type mismatch.    
Required: FlutterEngine!    
Found: MainActivity

The MainActivity Class:

import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.view.FlutterMain

class MainActivity : FlutterActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    GeneratedPluginRegistrant.registerWith(this) // here is the error: Type mismatch. Required: FlutterEngine! Found: MainActivity

    MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
      if (call.method == "helloFromNativeCode") {
        val greetings = helloFromNativeCode()
        result.success(greetings)
      }
    }
  }

  private fun helloFromNativeCode(): String {
    return "Hello from Native Android Code"
  }

  companion object {
    private const val CHANNEL = "flutter.native/helper"
  }
}

And if is use:

import io.flutter.embedding.android.FlutterActivity

instead of

import io.flutter.app.FlutterActivity

I can use

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }

but have trouble with:

MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
      if (call.method == "helloFromNativeCode") {
        val greetings = helloFromNativeCode()
        result.success(greetings)
      }
    }

because i get an error on flutterView:

Unresolved reference: flutterView

The code would look like this:

import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.view.FlutterMain

class MainActivity : FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result -> // here is the error
      if (call.method == "helloFromNativeCode") {
        val greetings = helloFromNativeCode()
        result.success(greetings)
      }
    }
  }

  private fun helloFromNativeCode(): String {
    return "Hello from Native Android Code"
  }

  companion object {
    private const val CHANNEL = "flutter.native/helper"
  }
}

I hope someone can help me.

Instead of flutterView use flutterEngine.getDartExecutor().

How to register plugins in io.flutter.embedding.android , Using a FlutterView requires forwarding some calls from an Activity , as well as forwarding lifecycle calls from an Activity or a Fragment . Launch Screen and� Step #1: Create a Flutter project and write code in main.dart file. Look at the below code, There is _methodChannel is an object of MethodChannel with the name of MethodChannel, remember the same…

I spent days trying to figure out how to add a Flutter UI to my existing Android App. The biggest challenge was getting the MethodChannel to work with FlutterActivity being called from MainActivity. I know this is a little different than the question asked here, but this post was returned when I did searches for 'Android FlutterActivity MethodChannel'. After going though many resources on how to do this, I finally found my solution here: https://github.com/flutter/samples/tree/master/add_to_app/android_using_plugin/app/src/main/java/dev/flutter/example/androidusingplugin

Initially, in Android Studio, with the existing app opened, I tapped File, New, New Module, Flutter Module. I received an error and had to perform manual steps.

My objective is to launch FlutterActivity (opens main.dart in the flutter_module) in MainActivity - onCreate, then develop Flutter 'screens' leveraging as much native Flutter code as possible, with limited Platform calls using the MethodChannel. As I develop replacement Flutter code, I will continue to comment out the existing Android Code.

Here is what finally worked for me:

../App_Project/Android/Existing_Android_App/settings.gradle
include ':app'
setBinding(new Binding([gradle: this]))
evaluate(new File(settingsDir.parentFile, '../flutter_module/.android/include_flutter.groovy'))
include ':flutter_module’
project(':flutter_module’).projectDir = new File('../../flutter_module’)
rootProject.name=‘existing_android_app’
../App_Project/Android/Existing_Android_App/app/build.gradle
dependencies {
…
    implementation project(':flutter')
}
../App_Project/Android/Existing_Android_App/app/src/main/AndroidManifest.xml
<activity
    android:name="io.flutter.embedding.android.FlutterActivity"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize" />
../App_Project/Android/Existing_Android_App/app/src/main/java/com/existing_android_app/MainActivity.java
package com.existing_android_app;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends AppCompatActivity {

    final String ENGINE_ID = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        FlutterEngine flutterEngine = new FlutterEngine(this);
        flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());

        FlutterEngineCache.getInstance().put(ENGINE_ID, flutterEngine);

        MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor(), "com.existing_android_app/myMethodChannel");

        channel.setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                        String url = call.argument("url");
                        if (call.method.equals("openBrowser")) {
                            openBrowser(url);
                        } 
                          else {
                            result.notImplemented();
                        }
                    }
                });

        startActivity(FlutterActivity.withCachedEngine(ENGINE_ID).build(this));
    }

    void openBrowser(String url) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));

        this.startActivity(intent);
    }
}
../App_Project/flutter_module/lib/home_page.dart
class AppHomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<AppHomePage> {

  static const platform = const MethodChannel(‘com.existing_android_app/myMethodChannel’);

  Future<void> _openBrowser() async {
    try {
      final int result = await platform.invokeMethod('openBrowser', <String, String> { 'url': "http://bing.com" });
    }
    catch (e) {
      print('***** _openBrowser error: ' + e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: CustomAppBar(),
        body: Column(
          children: <Widget>[
            RaisedButton(
              label: Text('Search',
                style: TextStyle(fontSize: 18.0),
              ),
              onPressed: () {  _openBrowser(); },
            ) // RaisedButton.icon
          ], // Widget
        ) // Column
      ) // Scaffold
    ); // SafeArea
  }

FlutterActivity, public class FlutterActivity extends Activity implements FlutterView. Returns the Flutter view used by this activity; will be null before onCreate(Bundle) is called. class MainActivity : FlutterActivity() { } First run flutter which is android activity. Step 2: static const MethodChannel _channel = const MethodChannel(‘flutter_plugin’); Create an instance of MethodChannel class with arguments: flutterView as the message sender/receiver and channel name. Note:

You should use

import io.flutter.embedding.android.FlutterActivity;

and declare your patformChannel in

     @Override
  public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);
    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
        .setMethodCallHandler(
          (call, result) -> {
            // Note: this method is invoked on the main thread.
            // TODO
          }
        );
  }

for more you can check the documentation: https://flutter.dev/docs/development/platform-integration/platform-channels

FlutterActivity MethodChannel和FlutterView, MethodChannel import io.flutter.plugins.GeneratedPluginRegistrant import io. flutter.view.FlutterMain class MainActivity : FlutterActivity()� Alternatives to FlutterActivity. If Flutter is needed in a location that cannot use an Activity, consider using a FlutterFragment. Using a FlutterFragment requires forwarding some calls from an Activity to the FlutterFragment. If Flutter is needed in a location that can only use a View, consider using a FlutterView.

MethodChannel in Flutter. How to access native(Android/IOS) code , Future<void> _getDocuments() async {MethodChannel _methodChannel or if using “override fun onCreate” then use “flutterView” in the MethodChannel parameter of BinaryMessenger. class MainActivity: FlutterActivity() { An in-depth introduction to Flutter’s platform channels. Learn how to connect your UI code written in Dart with platform-specific APIs on Android and iOS.

Flutter Platform Channels. “Nice UI. But how does Flutter deal…, This code can be added to a FlutterActivity subclass, typically Android side.val channel = MethodChannel(flutterView, "foo") channel. I am using Experimental:-Add-Flutter-Activity to add a Flutter Activity with my native android app, but some plugin are not work. I found that I didn't register plugins at all, Can anyone tell me how to do it at io.flutter.embedding.andr

How to register plugins in io.flutter.embedding.android , FlutterActivity MethodChannel 및 FlutterView. 약 4 개월 전에 Flutter 앱을 작성했습니다. 이제 작은 변경을 원했지만 GeneratedPluginRegistrant. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Comments
  • I am having the same issue. It looks like this got broken in the latest Flutter as they are switching to io.flutter.embedding.android.FlutterActivity