简体   繁体   中英

Cannot access the widget variable

I want to send widget.token to the User constructor but I cannot and it shows this error:

The instance member 'widget' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

This is my code:

 class HomeScreen extends StatefulWidget {
      final String token;
      const HomeScreen(this.token, {Key? key}) : super(key: key);
    
      @override
      createState() {
        return HomeScreenState();
      }
    }
    
    @override
    class HomeScreenState extends State<HomeScreen> {
      int _selectedIndex = 2;
      static const TextStyle optionStyle =
          TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
      static final List<Widget> _widgetOptions = <Widget>[
        User(widget.token),
        const Profile(),
        News(),
        SingleChildScrollView(
          child: Search(),
        ),
        ChartAl('null', 'Line'),
        // Home(),
      ];
    
      @override
      Widget build(BuildContext context) {
.....
...
...
..

Simply, you cannot use widget to initialize attributes of your state.

You should access it in the initState , or in the build function. Another possibility:

List<Widget> get _widgetOptions => <Widget>[
        User(widget.token),
        const Profile(),
        News(),
        SingleChildScrollView(
          child: Search(),
        ),
        ChartAl('null', 'Line'),
        // Home(),
      ];

Also, you can never access an instance variable in a static context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM