“Flutter如何将Java代码添加到Flutter模块中”

huangapple go评论76阅读模式
英文:

Flutter How to add java code to flutter module

问题

我想向Flutter模块添加一些Java代码。应该将Java代码添加到哪个目录?
我已经尝试将Java代码添加到如下图片底部所示的目录中,但是代码不会被编译成aar文件。

英文:

I want to add some java code to flutter module。Which directory should I add java code.
I have tried to add java code in the directory as picture bottom,but the code will not be compiled to aar.
“Flutter如何将Java代码添加到Flutter模块中”

答案1

得分: 1

你应该为执行一些 Java 代码实现平台通道。

**例如**,我正在从 Flutter 传递两个整数值到 Android Native。在 Android Native 端,Kotlin/Java 将对这些数字求和并将结果返回给 Flutter

**Flutter **

```dart
class Demo extends StatefulWidget {
  @override
  _DemoState createState() => _DemoState();
}

class _DemoState extends State<Demo> {
  static const platform = const MethodChannel('flutter.native/helper');

  @override
  void initState() {
    super.initState();
  }

  getData(int num1, int num2) async {
    try {
      final int result =
          await platform.invokeMethod('add', {'num1': num1, 'num2': num2});
      print('$result');
    } on PlatformException catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("Country"),
              SizedBox(
                height: 20.0,
              ),
              RaisedButton(
                onPressed: () => getData(10, 20),
                child: Text('Add'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Android Native 端

class MainActivity : FlutterActivity() {
    private val CHANNEL = "flutter.native/helper"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "add") {
                val num1 = call.argument<Int>("num1")
                val num2 = call.argument<Int>("num2")
                val sum = num1!! + num2!!
                result.success(sum)
            } else {
                result.notImplemented()
            }
        }
    }
}

注意:你应该在 iOS Native 端执行相同的操作,或者如果设备是 Android,则执行此方法,否则在 iOS 设备上会崩溃。


<details>
<summary>英文:</summary>

You should implement platform channel for executing some java code.

**For Example**, I am passing two int value from a flutter to Android Native. In the Android native side, Kotlin/Java will sum these numbers and return the result to flutter

**Flutter side** 

    class Demo extends StatefulWidget {
      @override
      _DemoState createState() =&gt; _DemoState();
    }
    
    class _DemoState extends State&lt;Demo&gt; {
      static const platform = const MethodChannel(&#39;flutter.native/helper&#39;);
    
      @override
      void initState() {
        super.initState();
      }
    
      getData(int num1, int num2) async {
        try {
          final int result =
              await platform.invokeMethod(&#39;add&#39;, {&#39;num1&#39;: num1, &#39;num2&#39;: num2});
          print(&#39;$result&#39;);
        } on PlatformException catch (e) {}
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            child: Center(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: &lt;Widget&gt;[
                  Text(&quot;Country&quot;),
                  SizedBox(
                    height: 20.0,
                  ),
                  RaisedButton(
                    onPressed: () =&gt; getData(10, 20),
                    child: Text(&#39;Add&#39;),
                  )
                ],
              ),
            ),
          ),
        );
      }
    }

**Android native side**

    class MainActivity : FlutterActivity() {
        private val CHANNEL = &quot;flutter.native/helper&quot;
    
        override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
            GeneratedPluginRegistrant.registerWith(flutterEngine);
            MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -&gt;
                if (call.method == &quot;add&quot;) {
                    val num1 = call.argument&lt;Int&gt;(&quot;num1&quot;)
                    val num2 = call.argument&lt;Int&gt;(&quot;num2&quot;)
                    val sum = num1!! + num2!!
                    result.success(sum)
                } else {
                    result.notImplemented()
                }
            }
        }
    }

**Note**: You should do the same thing in iOS native side or execute this method if the device is Android otherwise it will crash in iOS device 

</details>



huangapple
  • 本文由 发表于 2020年10月19日 12:06:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64421033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定