升级flutter到1.12后,用AS创建的flutter项目默认用了kotlin,但是我不会啊,我改成了java。
1、首先第一个问题,更改 gradle 版本,不然打开android 项目会build失败
项目\android\build.gradle
修改如下:
//classpath 'com.android.tools.build:gradle:3.5.0' classpath 'com.android.tools.build:gradle:3.3.0'
项目\android\gradle\wrapper\gradle-wrapper.properties
修改如下:
#distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip
具体的版本可以自己修改试一下
2、使用java
项目\android\app\build.gradle
删除如下几行:
apply plugin: 'kotlin-android' ... sourceSets { main.java.srcDirs += 'src/main/kotlin' } ... implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
项目\android\build.gradle
删除如下几行:
ext.kotlin_version = '1.3.50' ... classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
把这个文件夹删了:项目\android\app\src\main\kotlin。(最好是先复制到其它地方去)
然后自己创建了对应的java目录和文件:项目\android\app\src\main\java\com\xxx\xxx
由于新版本的flutter 使用了FlutterEngine,所以 MainActivity 的代码如下:
import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(FlutterEngine flutterEngine){ GeneratedPluginRegistrant.registerWith(flutterEngine); } }
3、如何使用 MethodChannel 和 flutter 通信
由于使用了 import io.flutter.embedding.android.FlutterActivity ,所以不能使用 getFlutterView() 获取 BinaryMessenger(继承io.flutter.app.FlutterActivity才有getFlutterView)。
当然不要试图去继承 io.flutter.app.FlutterActivity,然后修改 ,项目\android\app\src\main\java\io\flutter\plugins\GeneratedPluginRegistrant.java,GeneratedPluginRegistrant.java文件会在运行时动态改变,强制使用 FlutterEngine
试了很多方法,然后我打开 FlutterEngine 源码,查看了一下,找到了一个 dartExecutor 属性,再次点击 DartExecutor 发现它继承自 BinaryMessenger,完美
可以用 flutterEngine.getDartExecutor() 替换 getFlutterView(),修改后代码如下:
import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { private static final String CHANNEL = "com.xxx.xxx/map"; private MethodChannel methodChannel; @Override public void configureFlutterEngine(FlutterEngine flutterEngine){ GeneratedPluginRegistrant.registerWith(flutterEngine); methodChannel = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL); methodChannel.setMethodCallHandler( new MethodChannel.MethodCallHandler() { @Override public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call.method.equals("getLocationAddress")) { //do something } else { //没有对应方法 result.notImplemented(); } } } ); } }