Cretezy / redux_persist

Persist Redux State
https://pub.dartlang.org/packages/redux_persist
MIT License
130 stars 41 forks source link

NoSuchMethodError: The method '[]' was called on null. #27

Closed Albert221 closed 6 years ago

Albert221 commented 6 years ago

Hey! I just started implementing redux_persist, but came on an error as in the title. I've managed to fix it.

Look at my code:

@override
Future<String> load() {
  return Firestore.instance
      .collection('users')
      .document(temporaryUserKey)
      .get()
      .then((doc) => json.encode(doc.data));
}

I found the error, it's in the json.decode (from dart:convert of course) line. The problem is, that if the data is null, the correct value of this JSON encoded data is 'null' and the exception is thrown, because of this line (redux_persist.dart:154):

int savedVersion = versionedState['version'];

The reason why executing reaches that line is that if that's passing (redux_persist.dart:133):

if (loadedJson != null && loadedJson.isNotEmpty) {

It passes it, because the encoded value is tested for null and being empty, but 'null' is also null, but JSON encoded.

So, to fix that in user code I used this:

@override
Future<String> load() {
  return Firestore.instance
      .collection('users')
      .document(temporaryUserKey)
      .get()
      .then((doc) {
    final encoded = json.encode(doc.data);

    return encoded == 'null' ? null : encoded;
  });
}

But the problem is with the if condition given above. I can submit a Pull Request to fix that, just let me know if this issue is valid :)

Cretezy commented 6 years ago

Very clever on having the data in Firestore!

I'm going to be updating this library either at the end of the week or the weekend with exactly what you need. I'm reworking fully how loading/saving works, and will remove this issue.

But as you said your solution if fine for now. It won't depend on json anymore!

Also little cleanup:

@override
Future<String> load() {
  return Firestore.instance
      .collection('users')
      .document(temporaryUserKey)
      .get()
      .then((doc) => doc.data != null ? json.encode(doc.data) : null);
}
Cretezy commented 6 years ago

This was fix/changed/removed in 0.8.0-rc.0, let me know if that fixes your problem!

zhanguangao commented 5 years ago

@Cretezy It seems that this error will be thrown in version 0.8.2, try persistor.load() catch can avoid this error.

Cretezy commented 5 years ago

@zhanguangao That is a bug in your fromJson method, since data can be null, you have to handle that manually (this is intended)

zhanguangao commented 5 years ago

@Cretezy Your are right, thank you!