0

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'],
    );
  }
}
Karatekid430
  • 940
  • 11
  • 25
  • No, you cannot use factories with generics. But there are some workarounds. Check out this [thread](https://stackoverflow.com/a/55237197/19945688). – Soliev Mar 21 '23 at 08:54
  • I guess I could just make a constructor which takes a JSON string? – Karatekid430 Mar 21 '23 at 09:08
  • [There are many questions just like this one](https://stackoverflow.com/search?q=%5Bdart%5D+t.fromjson). `static` methods and constructors in Dart are not part of a type's interface. I strongly recommend using [`package:json_serializable`](https://pub.dev/packages/json_serializable) or [`package:built_value`](https://pub.dev/packages/built_value) and avoid implementing your own serialization/deserialization code. Alternatively pass around a `fromJson` callback appropriate for that type. – jamesdlin Mar 21 '23 at 18:15

0 Answers0