The instance member 'userId' can't be accessed in an initializer

Viewed 44

This is my code

static  List<Widget> pages =  <Widget>[
Device(),
ProfilePage(userId: userId), // Error Comes in this userId

];

This where I get "userId"

void initState() {
setState(() {
  userId = userInitializer.initializeUser()!;
  print(".................User Id...................");
  print(userId);
  print(".................User Id...................");
});
// TODO: implement initState
super.initState();

}

I have tried to solve this for a long time

1 Answers

You can't access class level variable in static code. Static variables are initialised when the app runs and by that time, the class object which contains the said variable is not initialised.

You will have to remove the static keyword from pages variable. You might still get error as global variables are evaluated and assigned value when the class object is created and in your case userId might not be initialised by then.

Better approach would be to change the pages into getter property. Something like

List<Widget> get pages => <Widget>[
    Device(),
    ProfilePage(userId: userId),
  ];

This way, every time pages property is accessed, a new List will be created (behind the scene) and will be returned so that it could be used in your build method.

Related