无法在初始化程序中访问实例“小部件”

时间:2021-02-12 22:47:17

标签: flutter

我在访问 _MenuScreenState 上的变量 user 时遇到问题:

class MenuScreen extends StatefulWidget {
  final User user;
  
  MenuScreen(this.user);
  @override
  _MenuScreenState createState() => _MenuScreenState();
}

class _MenuScreenState extends State<MenuScreen> {
  final User userInMenu = widget.user;
}

显示的问题是“无法在初始化程序中访问实例成员 'widget'。 尝试用不同的表达式替换对实例成员的引用。

1 个答案:

答案 0 :(得分:1)

您必须在 initState 中执行以下操作:

class MenuScreen extends StatefulWidget {
  final User user;
  
  MenuScreen(this.user);
  @override
  _MenuScreenState createState() => _MenuScreenState();
}

class _MenuScreenState extends State<MenuScreen> {
  User userInMenu = widget.user;

  @override
  void initState() {
    super.initState();
    userInMenu = widget.user;
  }

如果我的回答对您有帮助,请点赞,让其他人也能理解。谢谢