2

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) {
.....
...
...
..

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.