Dart set default value for parameter

Viewed 16390

in Flutter framework i'm trying to set default value for parameters as borderRadius, in this sample how can i implementing that? i get Default values of an optional parameter must be constant error when i try to set that, for example:

class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius;
  SimpleRoundButton({
  }):this.borderRadius = BorderRadius.circular(30.0);
}


class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius= BorderRadius.circular(30.0);
  SimpleRoundButton({
    this.borderRadius,
  });
}


class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius;
  SimpleRoundButton({
    this.borderRadius=  BorderRadius.circular(30.0)
  });
}

all of this samples are incorect

2 Answers

BorderRadius.circular() is not a const function so you cannot use it as a default value.

To be able to set the const circular border you can use BorderRadius.all function which is const like below:

class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius;
  SimpleRoundButton({
    this.borderRadius: const BorderRadius.all(Radius.circular(30.0))
  });

  @override
  Widget build(BuildContext context) {
    return null;
  }
}

Gunhan's answer explained how you can set a default BorderRadius.

In general, if there isn't a const constructor available for the argument type, you instead can resort to using a null default value (or some other appropriate sentinel value) and then setting the desired value later:

class Foo {
  Bar bar;

  Foo({Bar? bar}) : bar = bar ?? Bar();
}

Note that explicitly passing null as an argument will do something different with this approach than if you had set the default value directly. That is, Foo(bar: null) with this approach will initialize the member variable bar to Bar(), whereas with a normal default value it would be initialized to null and require that the member be nullable. (In some cases, however, this approach's behavior might be more desirable.)

Related