I am dealing with PlatformChannels
trying to communicate from Kotlin
to Flutter
. Trying actually to do what it is explained on the docs from flutter platform channels, but on the opposite direction:
The idea is to call a Flutter function from the configureFlutterEngine function on the MainActivity.kt class.
For that, i do, on Flutter side, main.dart (default example from Flutter):
class _MyHomePageState extends State<MyHomePage> {
static const platformChannel = const MethodChannel('myTestChannel');
@override
Widget build(BuildContext context) {
platformChannel.setMethodCallHandler((call){
print("Hello from ${call.method}");
return null;
});
//
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
//
//
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
],
),
),
);
}
}
And from the Kotlin side, i just try to call the flutter callback method on MainActivity.kt:
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "myTestChannel")
channel.invokeMethod("myTestChannel","the argument from Android")
}
But nothing is printed on the Flutter side when I run the code. No crashes or exception either.
You should be implement below way
Dart Code
method_channel_helper.dart
class AmazonFileUpload {
static const platform = const MethodChannel('amazon');
static StreamController<String> _controller = StreamController.broadcast();
static Stream get streamData => _controller.stream;
Future<BaseResponse> uploadFile() async {
try {
platform.setMethodCallHandler((call) {
switch (call.method) {
case "callBack":
_controller.add("");
break;
}
});
final Map result = await platform.invokeMethod('s3_upload');
return BaseResponse(result["success"], result["error"], "");
} on PlatformException catch (e) {
return BaseResponse(false, e.message, "");
}
}
}
home_page.dart
class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
AmazonFileUpload.streamData.listen((event) {
print("========$callbackFromKotlinToDart--------");
});
AmazonFileUpload().uploadFile();
@override
Widget build(BuildContext context) {
}
Android Code
class MainActivity : FlutterActivity(), TransferListener {
private val CHANNEL = "amazon"
var methodResult: MethodChannel.Result? = null
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
channel.setMethodCallHandler { call, result ->
methodResult = result
if (call.method == "s3_upload") {
//Add you login here
channel.invokeMethod("callBack", "data1")
}
}
}