This is my class:
class Source {
final int value;
Source({this.value = 1}) {
print("source = $value");
}
}
This is how I'm passing values:
Source(value: null); // prints null
Source(); // prints 1
The question is if I am passing null to value in first call, why doesn't it print 1, aren't they equivalent?
In your definition you are creating a default parameter.
value is being defined as 1 and will be the default value in the absence of any other value being assigned to that parameter. When you actively provide it null as a value, it takes precedence over the default.
#adlopez15 is the correct answer.
But if you want null to result in 1 you can do this:
class Source {
final int value;
Source({int value}) : value = value ?? 1 {
print("source = ${this.value}");
}
}
Related
Why does dart complain "The default value of an optional parameter must be constant". How do I make the map value constant
Map<String, int> toastDuration = {
"defaut": 4000,
};
void showToast({
BuildContext context,
String msg,
int msDuration = toastDuration["default"], // Error: The default value of an optional parameter must be constant
bool hidePrev = true,
}) {
....
}
I tried adding const but that didn't work as it expects map part to be a class.
int msDuration = const toastDuration["default"],
toastDuration["default"] can't be constant because it's an expression calculated later (Think about the fact you can put any string in the braces). You can do something similar like that:
const defaultToastDuration = 4000;
Map<String, int> toastDuration = {
"default": defaultToastDuration,
}
void showToast({
BuildContext context,
String msg,
int msDuration = defaultToastDuration,
bool hidePrev = true,
}) {
...
}
As the error message says The default value of an optional parameter must be constant. Think about what happens if you remove the default key from toastDuration. Instead of using a map here you can simply use the default value directly.
void showToast({
BuildContext context,
String msg,
int msDuration = 4000,
bool hidePrev = true,
})
Another problem in your original code is that if you change the default key to say 300, the showToast will break because default parameters must be constants.
static Location fetchById(int id) {
List<Location> locations = Location.fetchAll();
for (var i = 0; i < locations.length; i++) {
if (locations[i].id == id) {
return locations[i];
}
}
return null;
}
// if the condition is not true then return null when I try to return null or false it gives the error 'A value of type 'Null' can't be returned from the method 'fetchById' because it has a return type of 'Location'.
With null-safety feature in the dart language, you have to explicitly tell if you want to make a value nullable.
Define the return type with a ?, so dart knows that return value can be null.
static Location? fetchById(int id)
{
/// function body
}
Consider the following function:
BasicClass copyWith({
String id,
}) {
// some code behaving differently for 1) id is undefined and 2) id is explicit null
}
And consider the two parameters below:
Nothing (id is undefined)
copyWith();
Null (id is null)
copyWith(id: null);
in the copyWith method, is there any way I can make it behave differently for 1) and 2)
There is no way to differentiate null from "no parameter passed".
The only workaround (which is used by Freezed to generate a copyWith that supports null) is to cheat using a custom default value:
final undefined = Object();
class Example {
Example({this.param});
final String param;
Example copyWith({Object param = undefined}) {
return Example(
param: param == undefined ? this.param : param as String,
);
}
}
This requires typing your variables as Object though.
To fix that issue, you can use inheritance to hide the Object under a type-safe interface (again, see Freezed):
final undefined = Object();
class Example {
Example._();
factory Example({String param}) = _Example;
String get param;
void method() {
print('$param');
}
Example copyWith({String param});
}
class _Example extends Example {
_Example({this.param}): super._();
final String param;
#override
Example copyWith({Object param = undefined}) {
return Example(
param: param == undefined ? this.param : param as String,
);
}
}
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?
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();
...
}
When you have multiple parameters use like below
int findVolume(int length, int breadth, {int height = 4}) {
return length*breadth*height;
}
void main() {
var result = findVolume(2, 3);
print(result);
print("");
//Overriding the default parameter
var result2 = findVolume(1, 2, height: 5);
print(result2);
}
*===== output ======*
24
10
If you use [ ] instead of { } to declare local variables in function,
int findVolume(int length, int breadth, [int height = 12]) {
return length*breadth*height;
}
===== you can call like below ======
findVolume(3, 6);
findVolume(3, 6, 5);
All credits go to:- https://flutterrdart.com/dart-optional-default-parameters-function/
I am reading a boolean integer value from database (0 or 1).
Is there an simple solution to convert a boolean int to boolean string?
When I was saving the value to my database I was able convert the string to an int using a javascript ternary operator.
var i = result ? 1 : 0;
Is it possible to preform the opposite?
My current work-around is:
function boolIntToString(i) {
if (i == 1) {
return true;
}
else {
return false;
}
}
The expression i != 0 evaluates to boolean false if i = 0, or true otherwise, so to get true or false, you could simply write:
var theBool = i != 0;
If you want a string, you can call .toString() on that boolean result. Wrapping this into your function, you get:
function boolIntToString(i) {
return (i != 0).toString();
}
console.log(boolIntToString(1));
Note that your own function returns a boolean, not a string.