flutter - 在我的文本中像变量一样使用 sharedPreferences
问题描述
如何在我的Text
小部件中使用 sharedPreferences 数据?
节省SP:
sharedPreferences.setString("firstName", jsonResponse['firstName']);
sharedPreferences.setString("lastName", jsonResponse['lastName']);
阅读SP:
getUserDetails(String key) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final firstName = sharedPreferences.getString('firstName') ?? '';
final lastName = sharedPreferences.getString('lastName') ?? '';
print(firstName);
print(lastName);
}
但是如何使用我的firstName
和lastName
喜欢的文本变量?
我以这种方式尝试:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Code Land", style: TextStyle(color: Colors.white)),
actions: <Widget>[
FlatButton(
onPressed: () {
sharedPreferences.clear();
// sharedPreferences.commit();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
},
child: Text("Log Out", style: TextStyle(color: Colors.white)),
),
],
),
body: Center(child: Text(getUserDetails('firstName'))), <=== HERE
drawer: Drawer(),
);
}
解决方案
您实际上不能直接这样做,因为 sharedPreferences 实例需要awaited
用于。但是有一个使用该小部件调用的FutureBuilder
小部件,您可以执行以下操作:
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder<SharedPreferences>(
future: SharedPreferences.getInstance(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Scaffold(
body: CircularProgressIndicator(),
); //Just some placeholder loading widget
return Scaffold(
appBar: AppBar(
title: Text("Code Land", style: TextStyle(color: Colors.white)),
actions: <Widget>[
FlatButton(
onPressed: () {
snapshot.data.clear(); //Note instead of sharedPreferences we now use snapshot.data
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) => LoginPage()),
(Route<dynamic> route) => false);
},
child: Text("Log Out", style: TextStyle(color: Colors.white)),
),
],
),
body: Center(child: Text(getUserDetails('firstName', snapshot.data))),
//Here you just pass the already loaded sharedPreferences to your method and make the method return your result immediately instead of a Future
drawer: Drawer(),
);
},
);
}
}
我希望这回答了你的问题。
推荐阅读
- azure-cosmosdb - 请帮助解决将 TTL 插入 Comsos DB 的问题
- c - Intel-TSX:为什么 rtm 表现得很奇怪?
- r - R-从 PurpleAir 传感器读取 csv 文件并跳过某些行末尾包含非标准字符的错误位置
- api - 无法使用 Vue 和 Axios 从 API 获取数据
- python - AWS Elastic Beanstalk(Dash plotly 应用程序)- 502 Bad Gateway
- c - LLVM:基本块的顺序重要吗?
- html - html select标签在django模板中不起作用
- javascript - 如何使用 React TypeScript 将组件传递给道具?
- react-native - 反应导航v5自定义抽屉 - 无法调用堆栈onPress Drawer Text
- android - 在模块 guava-16.0.1.jar 和 listenablefuture-1.0.jar 中发现重复的类 com.google.common.util.concurrent.ListenableFuture