Home > Back-end >  What do these symbols mean ??= in flutter
What do these symbols mean ??= in flutter

Time:05-12

I find this in some class and am not sure what they do
?? , ??=

example :

cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;

CodePudding user response:

?? is used to provide default value for null cases.

int? a ;

int b = a?? 0;// it a is null b will get 0

b ??= value; Assign value to b if b is null; otherwise, b stays the same

cursorColor ??= selectionTheme.cursorColor ?? cupertinoTheme.primaryColor;

If cursorColor value is null, then it will use right part.

If it finds selectionTheme.cursorColor is equal to null, then it will return cupertinoTheme.primaryColor.

CodePudding user response:

Those are Null-aware operators.

let's say we have an int, and base on that we're going to complete our example, which it is like below:

int? item; // this one is currently null, since there's no value defined as default.
item ??= 10; // here we check if `item` is null define new value for `item`.
print(item); // and here, base on above codes, we should get 10 because in above code
// we've checked our `item` if it's not null, define a new value.

now base on above example, we can do:

item ??=5; // in this case, since item is not null, and we've a value for `item` 
// already, we should get 10.
print(item); // 10 will be print since in second operator checked null value for variable
// and in this case value wasn't null this time.

And another one ?? in this case is going to return value in left of operator in case left side of operator is not null, for example :

print(10 ?? 15); // this will return 10, because left side of operator isn't null.
print(null ?? 20); // this one will return 20, because left side of operator is null.

So base on your code, if we split your code in 2 part, your code is checking if cursorColor is null, it will try to return a new value base on second part of your code, which at that part, It will check for another null value.

  • Related