I want to retrieve List of String from native Android to flutter via Method Channel. This list of string is all contact phone number. My current code:
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("getContacts")) {
contacts = getContactList();
if (contacts != null) {
result.success(contacts);
} else {
result.error("UNAVAILABLE", "not avilable", null);
}
} else {
result.notImplemented();
}
}
});
In Flutter:
final Iterable result = await platform.invokeMethod('getContacts');
contactNumber = result.toList();
But I'm not getting any response from flutter. How to retrive just phone number from native android to 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.
Method channel is a named channel for communicating with the Flutter application using asynchronous method calls. Method calls are encoded into binary before being sent, and binary results received are decoded into Dart values.
Here is how i did it.
Android Native code (Send list with Strings):
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("samples.flutter.io/contact")) {
final List<String> list = new ArrayList<>();
list.add("Phone number 1");
list.add("Phone number 2");
list.add("Phone number 3");
result.success(list);
} else {
result.notImplemented();
}
}
}
);
Flutter Code:
List<dynamic> phoneNumbersList = <dynamic>[];
Future<List<String>> _getList() async {
phoneNumbersList = await methodChannel.invokeMethod('samples.flutter.io/contact');
print(phoneNumberList[0]);
return phoneNumberList;
}
Java side (sending data):
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine)
{
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "foo_channel")
.setMethodCallHandler((methodCall, result) -> {
if (methodCall.method.equals("methodInJava")) {
// Return your List here.
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
result.success(list);
}
});
}
Dart side (receiving data):
void getList() async {
var channel = MethodChannel('foo_channel');
List<String>? list = await channel.invokeListMethod<String>('methodInJava');
print(list); // [A, B, C]
}
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