Flutter调用Android原生方法的笔记记录

2020-07-05  本文已影响0人  Victor_Xu
flutter_android_anim.gif

1.环境

测试的环境信息

Flutter版本 pubspec.yaml

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

Android Studio 4.0 build.gradle

 defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28
        ...
    }

2.Flutter 调用Android代码示例

CHANNEL = "com.appgole/flutter" 随便定义,主要Flutter ,Android,IOS一致就行

//列表item点击
  _handleOnTab(BuildContext context, int index, Product product) async {
    getMsg().then(
      (value) => Scaffold.of(context).showSnackBar(SnackBar(
        content: Text(value),
      )),
    );
  }

  Future<String> getMsg() async {
    // Native channel
    const platform = const MethodChannel("com.appgole/flutter"); 
    String result = "no";
    try {
      result = await platform.invokeMethod("getMsg"); 
    } on PlatformException catch (e) {
      print(e.toString());
    }
    return result;
  }
}
flutter_android.png

3.Android端需要注册提供给Flutter调用的Channel以及Method

class MainActivity : FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        val channel = "com.appgole/flutter"
        val methodChannel = MethodChannel(flutterEngine.dartExecutor, channel)
        methodChannel.setMethodCallHandler { call, result ->
            if (call.method == "getMsg") {
                result.success(getMsg())
            } else {
                result.notImplemented()
            }
        }
    }
    private fun getMsg(): String {
        return "I am from Android"
    }
}
上一篇下一篇

猜你喜欢

热点阅读