Firebase:从背景消息中更新模型

发布于 2025-01-24 02:20:56 字数 792 浏览 0 评论 0原文

当我的应用在后台收到带有数据对象的消息时,我将如何实现模型的新状态? firebasemessaging.onbackgroundMessage()正在工作,我可以看到从服务器发送的数据,但我无法弄清楚如何使用此新数据来更新模型。将其分配给变量作品,但读取此变量后来返回null。我也使用GetIT,但在应用程序在后台时无法调用它。 所有的教程都显示如何接收数据(并将其打印到控制台中),但是在应用程序在后台时,没有一个显示如何实际使用它。

编辑:我已经检查了多个来源,这些来源描述了云消息传递,例如 https:// https:// 。他们中的大多数只是描述如何接收消息。示例:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}

我走了很远。我来自服务器的消息包含一个数据对象,该数据对象具有所需的模型值(例如:“ newbalance”:100.00)。但是,如何在其后台使用此新数据在我的应用中更新我的模型?我似乎无法访问它(如上所述,分配的变量以后返回null)。

How would I implement a new state of my model when my app receives a message with a data object from our server while in the background? FirebaseMessaging.onBackgroundMessage() is working and I can see the data sent from the server but I can't figure out how to update the model with this new data. Assigning it to a variable works but reading this variable later returns null. I'm also using GetIt but can't call it when the app is in the background.
All the tutorials just show how to receive the data (and just print it into console) but none show how to actually use it when the app is in the background.

Edit: I've checked multiple sources, which describe cloud messaging, for example https://firebase.flutter.dev/docs/messaging/usage/. Most of them just describe how to receive the message. Example:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}

I've got this far. My message from the server contains a data object, which has the required model values (for example: "newBalance" : 100.00). But how do I update my model in my app with this new data while it is in the background? I don't seem to have access to it (as described above the assigned variable later returns null).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

青衫负雪 2025-01-31 02:20:56

经过近一个星期的尝试,我认为我为自己的问题找到了解决方法。使用Hive包该应用程序将新数据写入本地数据库。但是,在应用程序在后台时,调用hive.initflutter()在应用程序中不起作用。因此,我在我的main() methot中将目录 path path 编写了目录(等待getapplicationDocumentsDirectory())。路径。然后,当该应用在后台收到消息时,我致电

if (Platform.isAndroid) {
  SharedPreferencesAndroid.registerWith();
} else if (Platform.isIOS) {
  SharedPreferencesIOS.registerWith();
}

(来自packages shared_preferences_android and code> and shared_preferences_ios_ios),然后我可以重述路径var dir =(等待sharedPreferences.getInstance())。getString(“ keyfordir”); for Hive。使用hive.init(dir)我能够打开框以在此处写入数据(box.close()之后)。最后,当该应用再次在前景中时,我可以从Hive中读取数据(不要忘记box.close()之后)。

PHEW,这是一个糟糕的解决方案,但这是唯一对我工作的方法。互联网上的其他一些人似乎有同样的问题( https://github.com/github.com/flutter.com/flutter /flutter/essess/98473 )和其他一些解决方案对他们有用,但对我不起作用。

After almost a week of trying I think I found a workaround for my problem. Using the hive package the app writes the new data to the local database. However, calling Hive.initFlutter() was not working, while the app was in the background. So I wrote the path to the directory (await getApplicationDocumentsDirectory()).path into SharedPreferences in my main() method. Then, when the app receives a message while in the background, I call

if (Platform.isAndroid) {
  SharedPreferencesAndroid.registerWith();
} else if (Platform.isIOS) {
  SharedPreferencesIOS.registerWith();
}

(from packages shared_preferences_android and shared_preferences_ios) and afterwards I can retreive the path var dir = (await SharedPreferences.getInstance()).getString("keyForDir"); for Hive. Using Hive.init(dir) I'm able to open the box to write my data there (box.close() afterwards). Finally I can read the data from Hive when the app is in the foreground again (don't forget box.close() afterwards).

Phew, what a bad solution but it's the only one working for me. Some other people on the internet seem to have the same problem (https://github.com/flutter/flutter/issues/98473) and some other solutions worked for them but not for me.

纵山崖 2025-01-31 02:20:56

您的选项是有限的,因为 documentation 说:

由于处理程序在应用程序上下文之外以其自身的隔离运行,因此无法更新应用程序状态或执行任何影响逻辑的UI。但是,您可以执行逻辑,例如HTTP请求,执行IO操作(例如更新本地存储),与其他插件进行通信。

但是,您 rel =“ nofollow noreferrer”>共享首选项插件要从您的背景消息处理程序中保存收到的数据,例如:

import 'package:shared_preferences/shared_preferences.dart';

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    final sharedPrefs = await SharedPreferences.getInstance();
    sharedPrefs.setString('data', <YOUR DATA FROM MESSAGE>);
}

由于您的应用程序此时在后台,因此您需要在恢复该值后获取此值。检查一个完整的示例在这里,但基本上您需要这样的东西在您的主要小部件中:

@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
  if (state == AppLifecycleState.resumed) {
    final sharedPrefs = await SharedPreferences.getInstance();
    final data = sharedPrefs.getString('data');
    print('Found in SharedPrefs: $data');
  }
}

之后,您可以找到一种方法来更新所需的内容,并且已经在您的应用程序上下文中。

Your options are limited, as the documentation says:

Since the handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can, however, perform logic such as HTTP requests, perform IO operations (e.g. updating local storage), communicate with other plugins etc.

For example you can use Shared preferences plugin to save the received data from your background message handler like:

import 'package:shared_preferences/shared_preferences.dart';

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    final sharedPrefs = await SharedPreferences.getInstance();
    sharedPrefs.setString('data', <YOUR DATA FROM MESSAGE>);
}

Since your application is in the background at this time, you need to fetch this value after it is resumed. Check for a complete example here, but basically you need something like this in your main widget:

@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
  if (state == AppLifecycleState.resumed) {
    final sharedPrefs = await SharedPreferences.getInstance();
    final data = sharedPrefs.getString('data');
    print('Found in SharedPrefs: $data');
  }
}

After this you can find a way to update anything you need, already within your application's context.

棒棒糖 2025-01-31 02:20:56

我正在使用firestore用于更新应用程序,sharedPreferences

onbackgroundMessage中没有工作

await Firebase.initializeApp().then((value) async {
  FirebaseFirestore.instance.collection('background').doc(dt1).set({
    "date": dt1,
    // add fields to the Doc
  }).then((value) async {
    FirebaseService.localNotificationsPlugin.show(
      0,
      "$title",
      "$body",
      FirebaseService.platformChannelSpecifics,
      payload: "$payload",
    )
  });

I'm using Firestore to update the App, the SharedPreferences didn't work

In onBackgroundMessage I'm doing the following

await Firebase.initializeApp().then((value) async {
  FirebaseFirestore.instance.collection('background').doc(dt1).set({
    "date": dt1,
    // add fields to the Doc
  }).then((value) async {
    FirebaseService.localNotificationsPlugin.show(
      0,
      "$title",
      "$body",
      FirebaseService.platformChannelSpecifics,
      payload: "$payload",
    )
  });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文