实例成员' userId'可以在初始化器中访问

发布于 2025-01-26 18:16:23 字数 508 浏览 4 评论 0原文

这是我的代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

£冰雨忧蓝° 2025-02-02 18:16:23

您无法在静态代码中访问类级变量。当应用程序运行时,静态变量将初始化,到那时,包含上述变量的类对象不会初始化。

您将必须从pages变量中删除static关键字。当创建类对象时评估和分配的全局变量,并且在您的情况下,您可能仍会遇到错误。

更好的方法是将页面更改为Getter属性。 这样的

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

方式,每次页面属性都会访问,将创建一个新列表(在场景后面),并将返回,以便可以在您的构建方法中使用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文