I am using Firebase and SharePreferences to store some values after authentication. I get this error "Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' " I am trying to store 2 Key value pairs as JSON into the sharedPreferences.
Here is my code. User.dart
class GoogleUser {
final String displayName;
final String photoUrl;
GoogleUser(this.displayName, this.photoUrl);
GoogleUser.fromJson(Map<String, dynamic> json)
: displayName = json['displayName'],
photoUrl = json['photoUrl'];
Map<String, dynamic> toJson() =>
{'displayName': displayName, 'phototUrl': photoUrl};
}
SharedPref.dart
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPref {
saveInfo(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value));
print("|||||||||||||||||||||||||||||||||||");
print(value);
}
deleteInfo(String key) async {
final prefs = await SharedPreferences.getInstance();
prefs.remove(key);
}
}
This the snippet which I use to save the user data, this is an file named as auth.dart, I get all the values push into sharedpreff.
void storeUserData(displayName, photoUrl) {
SharedPref sharedPref = SharedPref();
GoogleUser gUser = new GoogleUser(displayName, photoUrl);
String user = jsonEncode(gUser);
sharedPref.saveInfo('googleUser', user);
print(" Shared Prefs ");
print(user);
}
This is retrieve info code, in a file login.dart
void getInfo() async {
final prefs = await SharedPreferences.getInstance();
print(prefs.getString('googleUser')!);
Map<String, dynamic> jsonData = jsonDecode(prefs.getString('googleUser')!);
var userData = GoogleUser.fromJson(jsonData);
print(
"--------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>....----------------");
print(userData.displayName);
print(userData.photoUrl);
setState(() {
//(prefs.getString('googleUser'));
});
}
This is the print output for the first print statement in this method, The string appears different compared to how it got stored, and I get error on the line just after the first print statement. I am breaking my head on what is missing here. I referred this article to write this code, https://protocoderspoint.com/store-data-model-object-data-in-sharedpreferences-flutter/
Any help is much appreciated for a newbie Flutter developer
CodePudding user response:
I thinks its this line
prefs.setString(key, json.encode(value));
it should be:
prefs.setString(key, value);
since you already encoded the user to Srting in this line
String user = jsonEncode(gUser);