I have a class which tries to persist its state from SharedPreferences. The data in SharedPreferences has been verified to be valid JSON of class AuthResponse
.
class SharedPreferencesObserver<T> extends ChangeNotifier {
late String _keyParam;
T? _value;
SharedPreferencesObserver(String key) {
_keyParam = key;
final jsonString = SharedPreferencesManager.instance.getString(key);
try {
_value = json.decode(jsonString) as T;
} catch (e) {
_value = null;
}
}
}
The exception is thrown type '_Map<String, dynamic>' is not a subtype of type 'AuthResponse' in type cast
But I cannot use T.fromJson
even though this method is implemented, even if I change to T extends Jsonable
and define Jsonable
as an abstract class with that fromJson
field.
How can I call the fromJson
which is implemented in my AuthResponse
class, or otherwise successfully do a JSON parse? AuthResponse
is as follows:
class AuthResponse {
final String token;
AuthResponse({required this.token});
Map<String, dynamic> toJson() {
return {
'token': token,
};
}
factory AuthResponse.fromJson(Map<String, dynamic> json) {
return AuthResponse(
token: json['token'],
);
}
}