4

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

7
  • Do you want to run some java code and pass output to flutter? Commented Oct 19, 2020 at 4:57
  • For example : pass two integer number from a flutter to java and java sum this number and pass result from java to flutter? Commented Oct 19, 2020 at 4:58
  • @NikhilVadoliya Yes,the flutter module will be build as AAR, I want to add some java code to this aar Commented Oct 19, 2020 at 6:11
  • You should use Platform channel . Commented Oct 19, 2020 at 7:46
  • Please share your feature for need Java code so I will share the demo in Answer Commented Oct 19, 2020 at 7:47

2 Answers 2

1
+50

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

7 Comments

Thank you very much.But there is a problem.The MainActivity will not be compiled as it is a flutter module not application
you should open another project. First, you move your mouse pointer to the android folder and select android folder now click right button and select flutter. Click on the open android module.
I open the android module, and add java file at host directory, but the final artifact did not contain A.class or MainActivity.class It is shown in the picture ibb.co/FYmmX1g
I think you are not open proper file or SDK are not proper for compile
1、This is a flutter module not an application,the final artifact is aar file. 2、the aar file will not contain mainActivity class. As ibb.co/QFyGMWp
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.