chefish
chefish

Reputation: 595

Flutter How to add java code to flutter module

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. enter image description here

Upvotes: 4

Views: 3488

Answers (2)

Pavlo Ostasha
Pavlo Ostasha

Reputation: 16699

Basically, what you want is impossible from the pure Flutter module perspective because it uses autogenerated .android and .ios folders and ignores ones without dot. You can change those autogenerated files, but they will be rewritten with the new generation every time.

You have options:

  1. Create a script that automatically adds all the needed stuff to the generated files every time after generation
  2. Create an elaborate scheme with a native wrapper module for the flutter module and its means of communication inside with an exposed native(java, kotlin) interface to the main app. Some replacement of the autogenerated code and even flutter tools will still be required. More info here

Upvotes: 1

Nikhil Vadoliya
Nikhil Vadoliya

Reputation: 1578

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() => _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 side

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()
            }
        }
    }
}

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

Upvotes: 0

Related Questions