0

I want to get user data from SharedPreferences in json format. whenever I want to show this data in screen it will show on screen but in console it displayed this error "The method '[]' was called on null. Receiver: null Tried calling: ". the error are throwing by this code ${userData['id']}

class _ProfileState extends State<Profile> { var userData; void initState(){ getUserData(); super.initState(); } void getUserData() async{ SharedPreferences localStorage = await SharedPreferences.getInstance(); var userJson = localStorage.getString('user'); var user = json.decode(userJson); setState(() { userData = user; }); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Center( child: Text("Profile"), ), actions: <Widget>[LoginPopup()], ), drawer: AppDrawer(), body:Padding( padding: EdgeInsets.all(10), child: ListView( children: [ Container( child: Center( child: Text('${userData['id']}'), ), ), ], ) ), ); } } 

this is the error show in console

this will display the id but error is still in console

1 Answer 1

2

Yes, this happens because the first time you render your widget, you display userData which is null because you did not initialize the userData variable. So you can initialize it from the start like that

var userData = { "id": 0 }; 

or you can make a condition if userData is null like this

Text(userData != null ? "${userData['id']}" : "0") 

But then, you call setState and it will rebuild your widget and userData is no longer null because you get user data from SharedPreferences.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvote done. please check my another question. stackoverflow.com/questions/63701164/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.