如果需要与特定的API /硬件组件进行交互,您如何将信息从Flutter传递回Android /本机代码?
是否有任何事件通道可以通过其他方式或类似回调的方式发送信息?
这是一个简单的实现,展示了:
代码基于以下示例:https://flutter.io/platform- channels/#codec
1.传递字符串值“ text”:
String text = "whatever"; Future<Null> _getBatteryLevel(text) async { String batteryLevel; try { final String result = await platform.invokeMethod('getBatteryLevel',{"text":text}); batteryLevel = 'Battery level at $result % .'; } on PlatformException catch (e) { batteryLevel = "Failed to get battery level: '${e.message}'."; } setState(() { _batteryLevel = batteryLevel; });
}
2.在RandomFunction()之后获取响应“电池电量”;
public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (call.method.equals("getBatteryLevel")) { text = call.argument("text"); String batteryLevel = RandomFunction(text); if (batteryLevel != null) { result.success(batteryLevel); } else { result.error("UNAVAILABLE", "Battery level not available.", null); } } else { result.notImplemented(); } }
希望这可以帮助!