Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Flutter Function from Android Part of the App

I have an Android app that uses Flutter/Dart as a library.

When the app is closed it continues to run in the background as a service. In the Android code (in Java), I need to call a method that is written in the Flutter part of the app.

How can I do that? I found some posts mentioning the MethodChannel but I only found examples where the Flutter part calls a method from the native (Android) part. I want to do the opposite.

How can I do that?

Thank you.

like image 280
AJM Avatar asked Apr 04 '19 16:04

AJM


People also ask

How do you call a method in Flutter?

invokeMethod<T> method Null safety. Invokes a method on this channel with the specified arguments . The static type of arguments is dynamic , but only values supported by the codec of this channel can be used. The same applies to the returned result.

What is Methodchannel in Flutter?

Flutter Method ChannelsFlutter allows you to call platform-specific APIs (that are written in the OS native language) with the use of Platform Channels. Messages are passed from Flutter to the host operation system (either Android or IOS) where it is received and an action is carried out.


1 Answers

in Flutter, after creating MethodChannel instance, attach a MethodCallHandler like this:

_channel.setMethodCallHandler((call){
      print(call.method);
    });

And from your Android code do this:

channel.invokeMethod("hello","any argument");

However, it will not work when the app has been terminated even if a service is still alive. I have tested it.

like image 98
Ryosuke Avatar answered Oct 06 '22 13:10

Ryosuke