Is it possible to require only one of two parameters in Dart?

Viewed 1162

I know that I can require one parameter using @required like below :

class Foo{
  String firstParam;
  String secondParam;
  Foo({@required this.firstParam, this.secondParam});
}

However, I don't know how to require only one of the two parameters without requiring both. I have something that looks like what I want using assert :

class Foo{
  String firstParam;
  String secondParam;

  Foo({this.firstParam, this.secondParam}): assert(this.firstParam != null || this.secondParam!= null);
}

But it doesn't warn me in VS Code and asserts are not used in Release mode.

Is there some way to do it in Dart?

2 Answers

Use this and provide a message for your assertion:

class Foo {
  String firstParam;
  String secondParam;

  Foo({this.firstParam, this.secondParam})
      : assert(
          (firstParam != null || secondParam != null),
          'One of the parameters must be provided',
        );
}

Warning if none of the parameters is provided:

enter image description here

I think it's not possible, though you could make both parameters to be required and set explicitly to null if it is needed

Related