Reputation: 595
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.
Upvotes: 4
Views: 3488
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:
Upvotes: 1
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