错误“无法在初始化程序中访问实例成员 'widget'。”

时间:2021-06-19 04:54:21

标签: flutter

我尝试其他方法。但不工作。请帮我。谢谢

class AppBottom extends StatefulWidget {
  // This widget is the root of your application.
  final String appName;
  const AppBottom({Key? key, required this.appName}) : super(key: key); // 
  @override
  _AppBottomState createState() => _AppBottomState();
}

class _AppBottomState extends State<AppBottom> {
  int _selectedIndex = 0;
  List<Widget> _widgetOptions = [
    Home(appName: widget.appName), * error: The instance member 'widget' can't be accessed in an initializer.*
  ];
}

1 个答案:

答案 0 :(得分:1)

如错误所述,创建 widget 对象时无法访问 _AppBottomState。相反,您必须重写 initState 方法来初始化 _widgetOptions 列表。

class _AppBottomState extends State<AppBottom> {
  int _selectedIndex = 0;
  List<Widget> _widgetOptions;

  @override
  void initState() {
    _widgetOptions = [
      Home(appName: widget.appName),
    ];
    super.initState();
  }
  
}