Search code examples
flutterdartwidget

The instance member 'key' can't be accessed in an initializer


So basically I got an error that says The instance member 'key' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression when I try to make a StatefulWidget as shown below

class UserPage extends StatefulWidget {
  UserData userData;
  UserPage(this.userData) : super(key: key);
  @override
  State<StatefulWidget> createState() => new _UserPageState(userData);
}

any solution for this one? I tried to add 'late' at every point but it doesn't seem to work.


Solution

  • You should do something like this:

    class UserPage extends StatefulWidget {
      const UserPage({required this.userData, Key? key}) : super(key: key);
    
      final UserData userData;
    
      @override
      State<UserPage> createState() => _UserPageState();
    }