简体   繁体   中英

Dart set default value for parameter

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

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, 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM