实例成员' userId'可以在初始化器中访问
这是我的代码
static List<Widget> pages = <Widget>[
Device(),
ProfilePage(userId: userId), // Error Comes in this userId
];
我在这里得到“用户ID”
void initState() {
setState(() {
userId = userInitializer.initializeUser()!;
print(".................User Id...................");
print(userId);
print(".................User Id...................");
});
// TODO: implement initState
super.initState();
}
我已经尝试解决这个问题很长时间了
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法在静态代码中访问类级变量。当应用程序运行时,静态变量将初始化,到那时,包含上述变量的类对象不会初始化。
您将必须从
pages
变量中删除static
关键字。当创建类对象时评估和分配的全局变量,并且在您的情况下,您可能仍会遇到错误。更好的方法是将
页面
更改为Getter属性。 这样的方式,每次
页面
属性都会访问,将创建一个新列表(在场景后面),并将返回,以便可以在您的构建方法中使用。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 frompages
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 likeThis 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.