lesnitsky / flutter_localstorage

📦 LocalStorage for Flutter
MIT License
301 stars 60 forks source link

Data not typed after upgrade #67

Closed PeppeGiHub closed 2 years ago

PeppeGiHub commented 3 years ago

Hi

I migrated my Flutter application to use package version 3.0.6 + 9 instead of 3.0.0 + 3, but after this update my app started having problems reading data incorrectly. I save some json files on the disk and when I read this data it is not typed and I get this error: The type 'MyModel' is not a subtype of type 'Map<String, dynamic>'. I also reset the device , so wtitting file with new package, but the issue is still the same

I have now restored the package with this version localstorage: "<3.0.1" and my app is working fine

PeppeGiHub commented 3 years ago

Thanks for your reply

But do you mean i switch my all project with null-safety mode ?

tcd93 commented 3 years ago

I think I linked the wrong PR here. Sorry.

For your issue I regularly encounter it too, you have to write your own serialize/desirialize functions when storing and retrieving from hard drive because all will be interpreted as String type.

I'll post an example once I got home

tcd93 commented 3 years ago

Here is an example Image model class that has a method toJson and a named constructor method fromJson that deserialize/serialize image data into disk, local_storage will take care the rest for you

class Image {
  late String name;
  late Uint8List imageBytes;
  ...
  Image.fromJson(Map<String, dynamic> json)
      : id = json['name'],
        imageBytes =  Uint8List.fromList(List.castFrom<dynamic, int>(json['imageBytes']));

  Map<String, dynamic> toJson() {
    return 'name': name, 'imageBytes': imageBytes
  }
}

see more https://flutter.dev/docs/development/data-and-backend/json

lesnitsky commented 2 years ago

you have to deserialize your models from json. storage.getItem always returns json structures (maps, lists, primitives)