【问题标题】:How to store the flutter message data message on dart sidedart端如何存储flutter消息数据消息
【发布时间】:2021-07-25 07:47:55
【问题描述】:

如文档所述,处理后台消息时。

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

来自文档的后台处理程序代码部分。

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();

  print("Handling a background message: ${message.messageId}");
}

void main() {
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

执行 IO 操作(更新本地存储)的方式是什么?

【问题讨论】:

    标签: firebase flutter


    【解决方案1】:

    在本地存储数据有不同的方法。

    一个例子是使用shared_preferences 插件。

    当您收到这样的通知时,您可以写信给shared_preferences

    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('messageId', message.messageId);
    }
    
    Future<void> main() async {
      await Firebase.initializeApp();
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      runApp(MyApp());
    }
    

    当从后台收到消息时,上面的代码会将messageId 写入shared_preferences

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2020-07-21
      • 1970-01-01
      • 2023-03-17
      • 2021-06-01
      • 2018-11-27
      • 2017-11-13
      相关资源
      最近更新 更多