I have a background service in Android that I call in my Flutter Dart code using
var methodChannel = MethodChannel("org.daytonsquareroots.near.backgroundlocation");
methodChannel.invokeMethod("startBackgroundService", {
"encKey" : encryptionKey
});
I use a flutter library called simple rsa to encrypt location. However, Android doesn't seem to have an equivalent. So, my question is:
Can I call Dart code from my Android code like I do with the Flutter MethodChannel to call Android code?
I have checked this github issue, but there are no actual answers that I can find.
First, create the MyFirstDartProject folder. Secondly, on Android Studio, open the folder you have just created. Then create a new file: File > New > File > MyFirstDart.
Once you have created your project, you will see the “lib” folder where the “main. dart” file is located. Most importantly, once you have created a project and developed the application, Flutter expects the “main.
I don't know how effective it is but it works :D
private static final String CHANNEL = "widget.filc.hu/timetable";
// You have to run this on the main thread, i think
public static MethodChannel GetMethodChannel(Context context) {
FlutterMain.startInitialization(context);
FlutterMain.ensureInitializationComplete(context, new String[0]);
FlutterEngine engine = new FlutterEngine(context.getApplicationContext());
DartExecutor.DartEntrypoint entrypoint = new DartExecutor.DartEntrypoint("lib/main.dart", "widget");
engine.getDartExecutor().executeDartEntrypoint(entrypoint);
return new MethodChannel(engine.getDartExecutor().getBinaryMessenger(), CHANNEL);
}
The dart side has an init function like this:
void widget() async {
// get preferences everything what you want....
await app.settings.update();
// Create methodChannel
const MethodChannel channel = MethodChannel(CHANNEL);
channel.setMethodCallHandler(
(call) async {
final args = call.arguments;
print('on Dart ${call.method}!');
switch (call.method) {
case 'getTimetable':
return await _getTimetable();
case 'getRandom':
return Random().nextInt(100);
case 'initialize':
return "HELLO";
default:
throw UnimplementedError("Unknow: " + call.method);
}
},
);
}
These links are helped me:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With