Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value in function

Tags:

flutter

I try to set default value in function:

bool isOnGoing([DateTime date = DateTime.now()]) {
    ...
}

But studio returns "Default values of an optional parameter must be constant".

How can I set default parameter in this case?

like image 853
Andrey Turkovsky Avatar asked Oct 08 '18 12:10

Andrey Turkovsky


People also ask

How do you define a function with default value?

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

Can you assign the default values to a function parameters?

Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

What is the syntax for defining the default value of a function parameter?

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. function foo(a, b) { a = typeof a !==


1 Answers

The syntax you use is correct, but as the error message says, the value has to be a compile time constant.

A compile time constant doesn't make sense for DateTime.now().

As a workaround, you can use:

/// Returns `true` is still going on.
///
/// [date] the date to check.
///   as default value `DateTime.now()` is used 
///   if no value or `null` was passed.
bool isOnGoing([DateTime date]) {
    date ??= DateTime.now();
    ...
}
like image 57
Günter Zöchbauer Avatar answered Sep 18 '22 04:09

Günter Zöchbauer