gpt4 book ai didi

flutter - 在我的文本中像变量一样使用sharedPreferences

转载 作者:行者123 更新时间:2023-12-03 04:23:25 27 4
gpt4 key购买 nike

如何在我的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);
}

但是如何像文本变量一样使用 firstNamelastName

我以这种方式尝试:
  @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(),
);
},
);
}
}

我希望这回答了你的问题。

关于flutter - 在我的文本中像变量一样使用sharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61255708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com