Reputation:
How to use sharedPreferences data in my Text
widget?
saving sP:
sharedPreferences.setString("firstName", jsonResponse['firstName']);
sharedPreferences.setString("lastName", jsonResponse['lastName']);
reading sP:
getUserDetails(String key) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final firstName = sharedPreferences.getString('firstName') ?? '';
final lastName = sharedPreferences.getString('lastName') ?? '';
print(firstName);
print(lastName);
}
but how to use my firstName
and lastName
like a text variable?
i try in this way:
@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(),
);
}
Upvotes: 0
Views: 32
Reputation: 128
You actually can't do that directly, because the sharedPreferences instance needs to be awaited
for.
But there is a Widget called FutureBuilder
with that widget you could do something like:
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(),
);
},
);
}
}
I hope this answers your question.
Upvotes: 1