Operators for shorten code, Dart
Decent developers always recommend to keep their code as simple, clean, short and understandable as possible. For sure this approach is always a good practice.
You must also know about some advance dart operators to shorten your code and avoid boiler plate code. Lets start with these operators 🤩
Null aware operators
- ?? operator
Use this operator if you are returning any object just in case if it is not null, otherwise return some value.
It is same as
- ?? = operator
It also works almost the same as above but for assignment.
For example you have a variable and you want to assign a value to it only if it is null.
In the example below only if the number is null then 3 gets assigned to number.
The boiler plate for this example is
Using these operators, code became shorter and nicer. ✌️
- ?. operator
This operator is very important to avoid some unexpected errors with the first go of execution. Some times you have faced an error like
This called on null error came on
As you can see the names is null. When ever methods are called for a null object it gives called on null error. To avoid this error, we need to check the object if it is null or not and for this purpose we will use ‘ .? ’ operator.
More Operators
- Ternary operator
This one is a hack let’s say, very use full operator. It is handy operator to run expressions based on decision. If the situation is like
Then this can be shorten very smartly using ternary operator. eg
- .. operator
This is called cascade notation. It’s is used when more than one functions are being called for a single object. For example adding names to a list like this
will be as same as
- Spread operator ( … )
Spread operator is used when all the properties from a map or all the elements in list is poured to a new object or to a new list. For example we have two lists one containing name of vegetables and other containing names of fruits. Let’s say we have one more array containing the names of eatables and contains all elements from fruits and vegetables. Here spread operator helps us as
or same for map,
- Null aware spread operator
What if we are spreading elements from an object or list to another, but the source is null? Of course it will give us an error. Yes we can use if-else for checking for null, but OPERATORS. This ?… operator is used for null aware for spreading. Eg
This for sure helps you in certain places while coding in your dart project. 😎You can play around these operators quickly at https://dartpad.dev/