Issue
i am using flutter to make a widget AppBar Drawer and i saved datas in SharedPReferences... this is my Drawer.dart: class AppDrawer extends StatefulWidget {
@override
_AppDrawerState createState() => _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
SharedPreferences prefs;
Future<void> logOut() async {
final prefs = await SharedPreferences.getInstance();
prefs.clear();
Navigator.pushReplacementNamed(
context,
'/login',
);
}
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
child: Text(prefs.getString('first_name')),
decoration: BoxDecoration(
color: Colors.red,
),
),
ListTile(
leading: Text('LogOut'),
onTap: logOut,
),
],
),
);
}
}
the way i am using it to logout is working to clear them but when i want to use it in the widget build it give me a null response... i am trying to prefs.getString('first_name') but its giving me null :( what i am doing wrong here??
Solution
You need to implement it like.
class _AppDrawerState extends State<AppDrawer> {
String name = "";
SharedPreferences prefs;
@override
void initState() {
super.initState();
getName();
}
getName() async {
final prefs = await SharedPreferences.getInstance();
setState((){
name = prefs.getString('first_name');
});
}
Future<void> logOut() async {
prefs.clear();
Navigator.pushReplacementNamed(
context,
'/login',
);
}
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
child: Text(this.name),
decoration: BoxDecoration(
color: Colors.red,
),
),
ListTile(
leading: Text('LogOut'),
onTap: logOut,
),
],
),
);
}
}
await SharedPreferences.getInstance();
is an async call, you can't make an async call inside initState method or build widget method. So, that I created a separate function to get preferences and then updated the state variable name
.
Answered By - Ehtisham Shahid Abbasi Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.