Why is key required in constructor?

Viewed 1367

I have created class which extend StatefulWidget

class RegistrationPage extends StatefulWidget {
  final String email;

  const RegistrationPage({Key key, required this.email}) : super(key: key);

  @override
  _RegistrationPage createState() => _RegistrationPage();
}

The problem is android studio force me to put required before Key key. I googled some of examples how to pass values from screen to another screen and I have never seen that someone used required with Key. I do it within:

Navigator.push(
        context,
        new MaterialPageRoute(
          builder: (context) => RegistrationPage(email: email),
        ),
      );

so just to pass email value. I need to make Key nullable to make it work. Am I doing something wrong?

3 Answers

Because you're using null-safe Dart and key can't be null because it has a non-nullable type Key.

Solutions:

  • Use required

    FooPage({required Key key});
    
  • Make key nullable.

    FooPage({Key? key});
    
  • Remove key altogether.

    FooPage();
    

I think your project is in null safety, with null safety a variable or object cannot be null execept if it is declared nullable. Try adding a ? after Key:

class RegistrationPage extends StatefulWidget {
  final String email;

  const RegistrationPage({Key? key, required this.email}) : super(key: key);

  @override
  _RegistrationPage createState() => _RegistrationPage();
}

or you can simply delete the Key override:

class RegistrationPage extends StatefulWidget {
  final String email;

  const RegistrationPage({required this.email});

  @override
  _RegistrationPage createState() => _RegistrationPage();
}

I suggest you to read https://dart.dev/null-safety/understanding-null-safety

You're not doing anything wrong by making Key key nullable. The super constructors that you're passing the key to accept the nullable type.

So

const RegistrationPage({Key? key, required this.email}) : super(key: key);

is the norm as there is no reason to constrain the type by making it non-nullable and required.

If you have no need for keys with this widget, you can omit the super constructor and the key parameter completely.

Related