Flutter required keyword


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

class Test{
  final String x;
    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.


Dart 2.12 (null safety):

Beginning with Dart 2.12, the @required annotation is now replaced by the required keyword. You should mark your field required if it is mandatory for others to pass some value to it.

For example:

class Foo {
  final int a; // Mandatory? Use 'required'
  final int b; // Not mandatory? Don't use 'required'

    required this.a, // Marked 'required'
    this.b = 1, 


Foo(); // Error: 'a' is required
Foo(a: 0); // Good
Foo(a: 0, b: 1); // Good

Answered By – CopsOnRoad

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *