'_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

Viewed 626

I have this generic function:

  ValueType get<ValueType>(String keyToRead) {
    try {
      return _dataClient.get(keyToRead) as ValueType;
    } on SocketException catch (error) {...

And I call it like this:

  @override
  Map<String, dynamic> getUserRegistration() {
    return dataClient.get<Map<String, dynamic>>(UserRegistrationFieldKeys.self);
  }

but since I changed from using a get_storage box for my _dataClient to a hive box, I'm getting this error:

The following ProviderException was thrown building LoggedOutPageView(dirty, dependencies: [UncontrolledProviderScope], state: _ConsumerState#6c90b):
An exception was thrown while building AutoDisposeProvider<RegisterViewModel>#00006().

Thrown exception:
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

Stack trace:
#0      LocalDataClient.get
package:vepo/…/data_clients/local_data_client.dart:51
#1      UserRegistrationLocalDataSource.getUserRegistration
package:vepo/…/user_registration/user_registration_local_data_source.dart:22
#2      UserRegistrationRepository.getUserRegistration
package:vepo/…/user-registration/user_registration_repository.dart:31

Hive must store the data as a different format, possible due to encrypting, but how can I account for that and get rid of this error?

3 Answers

Try using

Map<String, dynamic>.from(dataClient.get(UserRegistrationFieldKeys.self))`;

And you can remove the generic function as well if you use this.

This is because your _dataClient.get(keyToRead) function returns an _InternalLinkedHashMap<dynamic, dynamic> datatype. When you assign a type Map<String, dynamic> to the output of the function like this: dataClient.get<Map<String, dynamic>>(), it means you are expecting the output of the function to be Map while it's not, thus causing error.

In this case, you should do the typecasting after getting the output of that function, something like:

 @override
  Map<String, dynamic> getUserRegistration() {
    return Map<String, dynamic>.from(dataClient.get(UserRegistrationFieldKeys.self));
  }

You can try this:

Map<String, dynamic> map = yourHiveBox.get("key").cast<String, dynamic>();
Related