Flutter: @required keyword

Little Monkey picture Little Monkey · Jan 14, 2019 · Viewed 9.7k times · Source

I don't really understand how @required works. For example I've seen this code:

class Test{
  final String x;
  Test({
    @required this.x
  });

  factory Test.initial(){
    return Test(x: "");
  }

}

But what should @required do here? Seems like it makes an optional parameter a non optional parameter.

Answer

Suragch picture Suragch · Jul 23, 2020

Update

As of Dart 2.12, the required keyword replaces the @required meta annotation. The following answer has been updated to reflect both this and null safety.

Parameters required by default

The parameters of a class constructor or function are required by default.

class Test {
  final String x;
  Test(this.x);
}

You're not allowed to do this:

final value = Test(); 
// 1 positional argument(s) expected, but 0 found.

You must do this:

final value = Test('hello');

Optional named parameters

If you surround a parameter with curly braces, though, in addition to becoming a named parameter, it also becomes optional.

Since it's optional, the property must either be nullable like this:

class Test {
  final String? x;
  Test({this.x});
}

Or it has to have a default value like this:

class Test {
  final String? x;
  Test({this.x = ''});
}

So now this is ok:

final value = Test(); 

And so is this:

final value = Test(x: 'hello'); 

Required named parameters

Sometimes a you don't want to allow a parameter to be null and there is no natural default variable. In that case you can add the add the required keyword in front of the parameter name:

class Test {
  final String x;
  Test({required this.x});
}

This is not ok anymore:

final value = Test(); 
// The named parameter 'x' is required, but there's no corresponding argument.

But this still is:

final value = Test(x: 'hello');