I have a problem with my code: my goal is to get data from sharedprefs and use the stored data afterwards. The problem is that the function where I get the data from sharedprefs is too slow, or in other words the function where I call the function for getting the data is too fast.
The process should be: in the main.dart
I call a function getDataString()
, which is in the sharedPreferences.dart
file, --> the function getDataString()
should get the data from sharedprefs --> the data should be printed.
With my code I get as result null, but when I print the variable savedData
a second time, I get the result I'm looking for. So I think that the getDataString function is simply too slow. How can I wait till the function is finished?
This is the code I tried:
This is the getDataString()
function from the sharedPreferences.dart
file:
Future<String> getDataString() async {
final prefs = await SharedPreferences.getInstance();
savedData = jsonDecode(prefs.getString("savedData"));
}
This is the initState
from the main.dart
:
void initState() {
super.initState();
getData();
log(savedData.toString());
});
}