flutter - 后台接收数据时如何将数据保存到Hive数据库中?

标签 flutter flutter-hive

当应用在后台时接收 Firebase Cloud Messaging (FCM) 推送通知数据时,我在将数据保存到 Hive 时遇到问题。

我有一个静态方法来像这样设置配置单元

static Future<void> setUpHive() async {
    try {

      await Hive.initFlutter();

      if (!Hive.isBoxOpen("Box Name")) {
          await Hive.openBox("Box Name");
      }

    } catch (error) {
      print(error.toString());
    }
}

我在 main 函数中使用 setUpHive 静态方法,如下所示

Future<void> main() async {

  await HiveHelper.setUpHive();

  runApp(
    MyApp(),
  );
}

当应用程序在后台时,然后它收到FCM消息,那么下面的代码将被调用。之后我尝试更改存储在 Hive 框中的数据

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    // when receive FCM message when app is in the background, this block will be executed
    
    // set up the hive first
    await HiveHelper.setUpHive(); 

    // then I try to change the data stored in the Hive box
    final myBox = Hive.box("BOX NAME");
    myBox.put("key", 12345);
}

收到 FCM 后台数据后似乎没问题,但是当我完全关闭应用程序并再次调用 main 时,尝试打开这样的框时出现错误

   static Future<void> setUpHive() async {
        try {

          await Hive.initFlutter();

          if (!Hive.isBoxOpen("Box Name")) {
              await Hive.openBox("Box Name"); // Error in this line
          }

        } catch (error) {
          print(error.toString());
        }
    }

错误是:

HiveError: This should not happen. Please open an issue on GitHub. E/flutter (13142): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: HiveError: This should not happen. Please open an issue on GitHub. E/flutter (13142): #0 BinaryReaderImpl.readFrame (package:hive/src/binary/binary_reader_impl.dart:250:7) E/flutter

我尝试寻找解决方案,并从here about Using Hive DB in a Background Process中发现类似的问题据说

leisim:

Unfortunately, Hive does not support opening boxes in multiple isolates. That means you can either close the box in the main isolate, update it in your background isolate and reopen it in the main isolate or you pass the data from the background to the main isolate and perform the update there...

我是Flutter新手,不太明白他说的是什么。请帮忙:(

最佳答案

您可以尝试以下代码。基本思想是将数据从后台isolate发送到主isolate。

Future<void> backgroundMessageHandler(RemoteMessage msg){
  IsolateNameServer.lookupPortByName('main_port')?.send(msg);
}

@override
void initState(){
  super.initState();

  ReceivePort receivePort = ReceivePort();
  IsolateNameServer.registerPortWithName(receivePort.sendPort,'main_port');

  receivePort.listen((message) {
    if(message is RemoteMessage){
      //TODO: save your data in hive box
    }
  }
    
}

关于flutter - 后台接收数据时如何将数据保存到Hive数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68678778/

相关文章:

flutter - 使用设置状态功能更新小部件

flutter - 从 Hive 盒中删除的对象仍会加载到内存中

Flutter Hive - 未处理的异常 : type 'List<dynamic>' is not a subtype of type 'List<SourceStations>' in type cast

flutter - 如何保存 List<Object> 并使用 Hive 检索?

flutter - 错误 : "type ' UnspecifiedInvalidResult' is not a subtype of type 'LibraryElementResult' in type cast"in Flutter Hive

listview - Flutter:使用 ListView 实现对来自 StreamBuilder 的数据的搜索功能

flutter - Dart 中的全局变量 : Singleton versus Static

flutter : Could not find package "build_runner"

android - 从网络下载 Artifact 时,Gradle 抛出错误。正在 Android Studio 中重试下载...

flutter - 无法运行 flutter 运行。得到一些 androidx 错误