5

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?

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
traki111
  • 361
  • 1
  • 3
  • 13

3 Answers3

4

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();
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • Which one is better. I know that I need to add '`?' or `required` – traki111 May 23 '21 at 17:24
  • 2
    @traki111 If you are definitely going to use `key`, use `required`, if definitely not, remove the `key` and if you're not sure use `Key?`. I've provided all the three possible solutions. – CopsOnRoad May 23 '21 at 17:27
2

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

Milvintsiss
  • 1,420
  • 1
  • 18
  • 34
2

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.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52