Home > Back-end >  The instance member 'key' can't be accessed in an initializer
The instance member 'key' can't be accessed in an initializer

Time:04-01

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 seems to work.

CodePudding user response:

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();
}

CodePudding user response:

The key param is not always required. So you can just delete the super part.

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