isar/hive

Map<String,dynamic> from Hive doesn't behave like a proper Map<String,dynamic>

开放

#522 创建于 2020年12月22日

 (17 条评论) (11 个反应) (0 位负责人)Dart (449 个派生)batch import
help wantedproblem

仓库指标

星标
 (4,394 个星标)
PR 合并指标
 (30 天内没有已合并 PR)

描述

Version

  • Platform: iOS, Android
  • Flutter version: 1.22.3
  • Hive version: 1.4.4
  • Flutter Hive version: 0.3.1

Hello guys, so I'm facing a difficulty understanding what type of Map does Hive returns. Below is my code:

Code sample

Future<List<Map<String, dynamic>>> readFromHive() async {
  final box = await Hive.openBox('storageName');
  final result = box.toMap().map(
        (k, e) => MapEntry(
          k.toString(),
          Map<String, dynamic>.from(e),
        ),
      );

  return result.values.toList();

  /// Let's say the result is:
  /// ```
  /// [ { name: 'John Doe', email: 'johndoe@gmail.com'} ]
  /// ```
}

final results = await readFromHive();

print(results[0]); // { name: John Doe, email: johndoe@gmail.com}
print(results[0]['name']); // null
print(results[0]['email']); // null
print(results[0].runtimeType) // _InternalLinkedHashMap<String, dynamic>

Here's the weird things:

  1. If it's not a Map<String,dynamic> why doesn't it crash the moment it exits the readFromHive()?
  2. If it's a Map<String,dynamic> why does print(results[0]['name']); prints null, while print(results[0]) prints correct result?
  3. I actually uses @JsonSerializable package. And I always need to pass anyMap: true in order for the fromJson to work properly. I never feels to pass anyMap: true if I don't deal with Hive.
  4. I use VS Code, and I put a breakpoint on the print statement. When I inspect the type of results[0], the type truly says Map<String,dynamic>

So, the question is like the title, why does it feels like Hive Map<String,dynamic> is not really acts like a Map<String,dynamic>? And how to make it a "true" `Map<String,dynamic>? Or is this intended? Maybe I misunderstand how Hive works?

Thanks

P.S. I can't use Hive's built in json parser since in a clean architecture, the entity and data source should not even care which local storage library I use.

贡献者指南