isar/hive

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

Aperta

#522 aperta il 22 dic 2020

 (17 commenti) (11 reazioni) (0 assegnatari)Dart (449 fork)batch import
help wantedproblem

Metriche repository

Star
 (4394 stelle)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

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.

Guida contributor