Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storing and retrieving documents changes their type signature #6

Open
olifly opened this issue Jun 9, 2021 · 1 comment
Open

Storing and retrieving documents changes their type signature #6

olifly opened this issue Jun 9, 2021 · 1 comment

Comments

@olifly
Copy link

olifly commented Jun 9, 2021

Hi.

When localstore stores a document it also saves the document to memory for faster retrieval. The problem is that in doing so it makes the types returned by a cached document vs uncached documents to be different and thereby breaking json marshal/unmarshal.

The following code should demonstrate this problem:

class JsonInner {
  final String val1;
  final bool val2;

  JsonInner(this.val1, this.val2);
  JsonInner.fromJson(Map<String, dynamic> json): this(json['val1'],json['val2']);
  
  Map<String, dynamic> toJson() => {
        'val1': val1,
        'val2': val2,
      };
}
class JsonOuter {
  final JsonInner inner;

  JsonOuter(this.inner);
  JsonOuter.fromJson(Map<String, dynamic> json): this(JsonInner.fromJson(json['inner']));

  Map<String, dynamic> toJson() => {
    'inner': inner,
  };  
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final db = Localstore.instance;

  JsonOuter ob1 = JsonOuter(JsonInner("Inner", true));
  String key = "uno";
  String collectionName = "deus";

  var data = await db.collection(collectionName).doc(key).get();
  if(data == null) {
    log("Data is null. Storing");
    db.collection(collectionName).doc(key).set(ob1.toJson());
    log("Data stored. Now run me again!!");
    return;
  } else {
    log("We got data: $data");
    log("Unmarshalling the data to an object will work");
    log("Unmarshal: ${JsonOuter.fromJson(data).toString()}");
    log("Storing again and retrieving");
    db.collection(collectionName).doc(key).set(ob1.toJson());
    data = await db.collection(collectionName).doc(key).get();
    log("Data is now: $data");
    log("Unmarshalling the data to an object will fail because type of 'inner' is not the same as when you read from file");
    log("Unmarshal: ${JsonOuter.fromJson(data!).toString()}");
  }
}
@ekasetiawans
Copy link

You have to use inner.toJson in JsonOuter.toJson too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants