gpt4 book ai didi

xamarin - Flutter 中的 Xamarin MessagingCenter 相当于什么?

转载 作者:行者123 更新时间:2023-12-03 03:57:15 28 4
gpt4 key购买 nike

Xamarin , 我们一般用Message-Center在应用程序运行时向任何页面发送消息(启动应用程序或应用程序是后台)。

Flutter ,我们有什么方法可以发送与 Message-Center 相同的消息吗?的 Xamarin.Forms ?

最佳答案

根据我的研究,您可以使用 Channel实现这一目标。
enter image description here
BasicMessageChannel是一个类似的 channel 。

原生部分 .

    private final Activity activity;
private final BasicMessageChannel<String> messageChannel;

static BasicMessageChannelPlugin registerWith(FlutterView flutterView) {
return new BasicMessageChannelPlugin(flutterView);
}

private BasicMessageChannelPlugin(FlutterView flutterView) {
this.activity = (Activity) flutterView.getContext();
this.messageChannel = new BasicMessageChannel<>(flutterView, "BasicMessageChannelPlugin", StringCodec.INSTANCE);
//Set up a message handler to handle messages from Dart
messageChannel.setMessageHandler(this);
}

@Override
public void onMessage(String s, BasicMessageChannel.Reply<String> reply) {//Handle messages from Dart
reply.reply("BasicMessageChannel:" + s);//Can reply by `reply`
if (activity instanceof IShowMessage) {
((IShowMessage) activity).onShowMessage(s);
}
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}

/**
* Send Dart a message and receive feedback from Dart
*
* @param message Content of the message to send to Dart
* @param callback Feedback from Dart
*/
void send(String message, BasicMessageChannel.Reply<String> callback) {
messageChannel.send(message, callback);
}

@Override
public void reply(String s) {

}
}

Dart 部分
import 'package:flutter/services.dart';
static const BasicMessageChannel _basicMessageChannel =
const BasicMessageChannel('BasicMessageChannelPlugin', StringCodec());

//Use BasicMessageChannel to receive messages from Native and reply to Native
_basicMessageChannel
.setMessageHandler((String message) => Future<String>(() {
setState(() {
showMessage = message;
});
return "receive Native's message:" + message;
}));
//use BasicMessageChannelsend message to Native And accept Native's reply
String response;
try {
response = await _basicMessageChannel.send(value);
} on PlatformException catch (e) {
print(e);
}

这是关于它的博客。
https://stablekernel.com/flutter-platform-channels-quick-start/

关于xamarin - Flutter 中的 Xamarin MessagingCenter 相当于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60042055/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com