美文网首页
Flutter调用Android原生方法的笔记记录

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

作者: Victor_Xu | 来源:发表于2020-07-05 13:27 被阅读0次
    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"
        }
    }
    

    相关文章

      网友评论

          本文标题:Flutter调用Android原生方法的笔记记录

          本文链接:https://www.haomeiwen.com/subject/nkkvqktx.html