8

The code is part of this class

   class Category extends StatelessWidget {

      final String name;
      final ColorSwatch color;
      final IconData iconLocation;

And the use of required is this:

    const Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })  : assert(name != null),
        assert(color != null),
        assert(iconLocation != null),
        super(key: key);

The use of Key key also confuses me.

jsdaniell
  • 390
  • 2
  • 5
  • 12

2 Answers2

18

The @required annotation indicates that the parameter is a required parameter (i.e an argument needs to be passed to the parameter).
You can instead create the function parameters without using the optional parameter syntax which implicitly makes it a required.

ie This

 Category(
    this.name,
    this.color,
    this.iconLocation,

 )  

Instead of

 Category({
    Key key,
    @required this.name,
    @required this.color,
    @required this.iconLocation,
  })    

Why use the optional parameter syntax together with the @required annotation?

The major benefit of doing it this way is readability! It helps when passing values to your widget fields since you don't have to guess the position of the parameters.

according to Dart's Language tour

Flutter instance creation expressions can get complex, so widget constructors use named parameters exclusively. This makes instance creation expressions easier to read.

Tayan
  • 1,707
  • 13
  • 18
nonybrighto
  • 8,752
  • 5
  • 41
  • 55
0

When you are creating object this keyword @required makes it required(needed).

Dart Language Tour

A function can have two types of parameters: required and optional. The required parameters are listed first, followed by any optional parameters. Named optional parameters can also be marked as @required. See the next section for details.

read about required

cipli onat
  • 1,943
  • 1
  • 11
  • 26