-1

Guys,why it is an obligation to put the 'required' keyword when creating named constructors? How can i create named constructors without being required thought?

  class IconPage extends StatelessWidget {
  
  IconPage({required this.icon,required this.label});
  final String label;
  final IconData icon;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          icon,
          color: Colors.white,
          size: 70,
        ),
        SizedBox(height: 10),
        Text(
          label,
          style: kStandartFontSize,
        ),
      ],
    );
  }
} 

Here's the error message that apears when i try to create named constructors without the required keyword:

The parameter 'label' can't have a value of 'null' because of its type, but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required' modifier.

2 Answers2

3

The required keywords means that the paramater is mandatory. If you don't want to use required you have to change your variable to be nullable with the ?. But then you have to make sure that you handle your parameters which can be null.

 class IconPage extends StatelessWidget {
  
  IconPage({this.icon, this.label});
  final String? label;
  final IconData? icon;

  ...
} 
quoci
  • 2,940
  • 1
  • 9
  • 21
1

As a compliment to the other answer:

You created your constructor using named parameters. They are called named parameters because when you call your function, you call it like this:

function (namedParameter1: "abc", namedParameter2: "123");

So you can change the order of parameters or not call one parameter at all.

One way to "not use the required keyword" would be to not use named parameters, but the regular "positional parameters":

IconPage(this.icon, this.label);

In this case, the order of the parameters you pass would matter, and all of them would be required by default.

So it should be called like this:

IconPage(IconData(...), "abc"),

Although this is not so common when writing custom Widgets (and I don't recommend it also), with simpler functions this can be used without compromising the readability. You can read more about the difference between positional and named parameters here.

Naslausky
  • 3,443
  • 1
  • 14
  • 24