试图通过SharedPreferences获取存储的数据,但是不起作用..
我的main.dart:
Widget build(BuildContext context) {
return StreamProvider<User>.value(
value: AuthService().user,
child: FutureBuilder<String>(
future: SaadConstants.setValueFromLocal('app_lang','ar'),
builder: (BuildContext context, AsyncSnapshot<String> snapshot){
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body:Wrapper(),
),
);
}
),
);
}
我的包装器:
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
if (user==null) {
return FutureBuilder(
future: SaadConstants.getValueFromLocal('app_lang'),
builder: (BuildContext contect , AsyncSnapshot<String> snapshot){
if (snapshot.hasData) {
return Text('has data');
}
else return Text('None');
}
);
}
else{
return Text('connect');
}
它返回此小部件:Text('None')..
我的setValue函数:
static Future<String> setValueFromLocal(String key, String value) async { // Async func to handle Futures easier; or use Future.then
SharedPreferences perfs = await SharedPreferences.getInstance();
perfs.setString(key.toString(),value.toString());
}
我的getValue函数:
static Future<String> getValueFromLocal(String key) async { // Async func to handle Futures easier; or use Future.then
SharedPreferences perfs = await SharedPreferences.getInstance();
return perfs.getString(key);
}
答案 0 :(得分:2)
尝试一下,
return FutureBuilder(
future: SaadConstants.getValueFromLocal('app_lang'),
builder: (BuildContext contect, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.hasData)
return Text("DATA: ${snapshot.data}");
else if (snapshot.hasError)
return Text("ERROR: ${snapshot.error}");
else
return Text('None');
}
);
您的main.dart也应满足这些条件。
Widget build(BuildContext context) {
return StreamProvider<User>.value(
value: AuthService().user,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: FutureBuilder<String>(
future: SaadConstants.setValueFromLocal('app_lang', 'ar'),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.hasError)
return Text("ERROR: ${snapshot.error}");
else
return Scaffold(
body: Wrapper(),
);
}
),
),
);
}