Reputation: 13
I am wondering why booleans work with either single or double equals in Dart, while the same is not true for other types like String
this works:
void main() {
bool a = true;
bool b = true;
if (a == b) {
print('Hello, World!');
}
}
This works, too:
void main() {
bool a = true;
bool b = true;
if (a = b) {
print('Hello, World!');
}
}
but this fails (does not compile):
void main() {
String a = 'true';
String b = 'true';
if (a = b) {
print('Hello, World!');
}
}
But my main motivation why I've started the post is that: the same logic (single equals) does not work in my code (double is OK, and finding this took my two days). What I mean is below code compiles but condition with single equal never satisfies unless i use double equals:
if (gxcG.findWealth(model.symbol).value.isstillowned =
false)
{
gxcG.marketOBought.forEach((element) {
if (element.value.symbol ==
model.symbol) {
element.value.isstillowned = false;
}
}),
if (model.portfolioname != null)
{
gxcForRO
.find(true, model.portfolioname!)
.value
.marketOBought = gxcG.marketOBought,
},
gxcG.wealth.removeWhere((element) =>
element.value.symbol == model.symbol),
},
gxcG is a GetXController extended class, and 'findWealth' method is as below:
Rx<WealthModel> findWealth(String symbol) {
return wealth.firstWhere((element) => element.value.symbol == symbol);
}
Upvotes: 0
Views: 67
Reputation: 31219
What you are doing here:
bool a = true;
bool b = true;
if (a = b){
Is setting a
to b
and then return the value assigned to a
. Since this value is a boolean, this is "allowed" but should really not be something you are doing since it is horrible (also, you are changing a
instead of just comparing).
You can see this change if you print a
and b
afterwards in an example like this:
void main() {
bool a = true;
bool b = false;
if (a = b) {
print('Hello, World!');
}
print(a); // false
print(b); // false
}
The reason why this example fails:
void main() {
String a = 'true';
String b = 'true';
if (a = b) {
print('Hello, World!');
}
}
Is because we set a
to the value of b
and return this value to the if-statement. But since b
is a String
, we cannot use this in our if-statement since it needs an expression resulting in a boolean.
Here is an (quick) example of how this syntax "can" be helpful:
void main() {
String a;
if ((a = getData()).isNotEmpty) {
print('We got data: $a'); // We got data: Here is some data
}
}
String getData() => 'Here is some data';
So since (a = getData())
will return the value we assign to a
(so a String
in this case) we can use that to ask if this value is empty or not.
Upvotes: 2