How to set a default value for an optional positional parameter of type Function?

Atomycon

I am passing a Function as an optional parameter to the constructor but I can't assign a default value.

void main() {
  Person p = Person();
  print(p.foo('Hello'));
}

class Person {
  final String Function(String) foo;
  Person({this.foo});
}

now trying to assign a default value: Person({this.foo = (val) {return val;}); produces the error: Error: Not a constant expression. I am aware the parameter must be const but using const or even static infront of (val) {return val;} does not work.

Does anyone have an idea how to solve this problem?

lrn

You can only use constant values (aka. compile-time constants) as default values. You cannot create a constant function literal, so there is no way to write the function in-line in the constructor.

However, references to top-level or static functions are constants, so you can declare the default value function as a static function or top-level function.

void main() {
  Person p = Person();
  print(p.foo('Hello')); // Prints "Hello"
}

class Person {
  final String Function(String) foo;
  Person({this.foo = _identity});
  static String _identity(String value) => value;
}
// or as top-level.
// String _identity(String value) => value;

You can (and should) choose to make the function public if the default value is on an instance method, and you expect anyone to extend or implement your class. In that case, they need to declare the same default value.

Another option, which is often at least as useful, is to not use a default value, but replace a null before using the value:

class Person {
  final String Function(String) foo;
  Person({String Function(String) foo}) : foo = foo ?? _identity;
  static String _identity(String value) => value;
}

or even using a non-constant value:

class Person {
  final String Function(String) foo;
  Person({String Function(String) foo}) : foo = (foo ?? (String x) => x);
}

For a constructor, it makes very little difference. If it was an instance method instead, using ?? to replace null avoids subclasses having to use the exact same function as default value.

Personally I recommend always using ?? instead of a default value. It's more flexible since it allows non-constant values. For non-function default values, you'll have to document the default behavior instead of just letting the dartDoc show {int x = 42}, but for functions, you'll have to document them anyway.

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How to change default value of optional function parameter

How to set default value in function

Flutter: How to handle "The default value of an optional parameter must be constant"

How to code optional default annotation value for Annotation TYPE

Why the default value of an optional parameter must be specified by a constant expression, or a parameterless constructor of a value type?

How to know whether a optional function parameter was passed or is it using the default function parameter?

Override the value of default parameter while there are optional parameters

How do I set a default value for a parameter in Rails?

Is It Possible To Set Default Parameter Value On A Rest Parameter

How can I inspect what is the default value for optional parameter in ruby's method?

How to only pass an optional parameter to a PHP function by keeping all other mandatory/optional parameters(if any) equal to their default values?

C# set a default for a type parameter

How to implement "positional-only parameter" in a user defined function in python?

How To Pass An Optional Parameter Inside a function of ggplot

Omitting parameter with default value in a subclass function override

Why can't use let to declare a variable using the same name as one function parameter, even the parameter get set default value?

Dart Flutter: The default value of an optional parameter must be constant when setting a default value to class constructor

How do I assign a default value to a function parameter that is a function? C++

How to set default value for variable?

How to set default value to param that has type keyof (from an explicit type) in Typescript

Action as a optional parameter in a function

Optional parameter in Arrow Function

VBA Function returning #VALUE! when trying to refer to Optional Parameter

How to type function return type with optional object of formatter function

How to pass a VPC's ID as a parameter to the Cluster.template to set as a default value?

How to set DEFAULT in SQL Parameter.AddWithValue

How to apply optional value to an optional function in F#

TypeScript: How to set function return value type based on function argument type

Default value in function parameter retained from previous function call

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo