My code here:
//get data
Future<Object> sharedGetData(String key) async{
SharedPreferences prefs=await SharedPreferences.getInstance();
return prefs.get(key);
}
setdata part :
sharedAddData(String key,Object dataType,Object data) async{
SharedPreferences prefs=await SharedPreferences.getInstance();
switch(dataType){
case bool:
prefs.setBool(key, data as bool);break;
case double:
prefs.setDouble(key, data as double);break;
case int:
prefs.setInt(key, data as int);break;
case String:
prefs.setString(key, data as String);break;
case List:
prefs.setStringList(key, data as List<String>);break;
default:
prefs.setString(key, data as String);break;
}
}
And then I added one and want to fetch one value:
//add
sharedAddData(Application.USER_LOGIN, bool, true);
//How to fetch this?
sharedGetData(Application.USER_LOGIN)
return a future type,but I want to check its value.
I have tried this way:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context){
sharedGetData(Application.USER_LOGIN).then((v){
if(v==true){
return MaterialApp(
home: DashboardScreen(),
);
}
else {
return MaterialApp(
home: LoginScreen(),
);
}});
}
}
But it reports that it lacks some return ways. Could anyone help me? thanks
your sharedGetData returns future so you can only get it with await. Now await needs function to be async which we cannot make build method. so we need to use FutureBuilder.
Try something on this line
class MyWidget extends StatelessWidget {
@override
Widget build(context) {
return FutureBuilder<String>(
future: sharedGetData(Application.USER_LOGIN),
builder: (context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
if(v==true){
return MaterialApp(
home: DashboardScreen(),
);
}
else {
return MaterialApp(
home: LoginScreen(),
);
} else {
return CircularProgressIndicator();
}
}
);
}
}