Hello Iam a newbie in Flutter and i need help.
My use case is, i have a UserClass, a SharedPreferencesModel and a DashboardScreen with UserData fetch from the internet. But UserData is stored in cache and by call the Function 'loadUser' with the 'readData'-Function from the SharedPreferencesModel inside, no filled the object User from the UserClass...
Here the UserClass:
class User {
final String firstname;
final String lastname;
final String club;
final String year;
final String gender;
User({this.firstname, this.lastname, this.year, this.club, this.gender});
factory User.fromJson(Map<String, dynamic> json) {
return new User(
firstname: json['firstname'],
lastname: json['lastname'],
year: json['year_of_birth'],
club: json['club'],
gender: json['gender']);
}
Map<String, dynamic> toJson() {
return {
'firstname': this.firstname,
'lastname': this.lastname,
'club': this.club,
'year_of_birth': this.year,
'gender': this.gender,
};
}
}
Here is my SharedPreferencesModel:
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesModel {
// save
storeData(String key, value) async {
final preferences = await SharedPreferences.getInstance();
await preferences.setString(key, jsonEncode(value));
}
// read
readData(String key) async {
final preferences = await SharedPreferences.getInstance();
return jsonDecode(preferences.getString(key));
}
// remove
deleteData(String key) async {
final preferences = await SharedPreferences.getInstance();
preferences.remove(key);
}
}
Here is a Snippet of the Widget:
SharedPreferencesModel data = new SharedPreferencesModel();
User userDataLoad = new User();
loadUser() async {
try {
// Data are displayed as json in the debugging-terminal
print(await data.readData("user"));
// something its wrong here
User user = User.fromJson(await data.readData("user"));
// "Test 2" is not displayed
print("Test 2");
Scaffold.of(context).showSnackBar(SnackBar(
content: new Text('Daten werden geladen...'),
duration: const Duration(milliseconds: 1000)));
userDataLoad = user;
} catch (Exception) {
Scaffold.of(context).showSnackBar(SnackBar(
content: new Text('Keine Daten gefunden!'),
duration: const Duration(milliseconds: 1000)));
}
}
void initState() {
super.initState();
loadUser();
// only for testing
print("test 1");
}
@override
Widget build(BuildContext context) {
...
Thanks for any help!