Junior
Tell about the operators in the Dart programming language.
sobes.tech AI
Answer from AI
Operators in Dart are used to perform operations on variables and values.
Main categories of operators:
- Assignment: Assigns a value to a variable.
int a = 10; // Assignment a += 5; // a = a + 5 a ??= 0; // Assign 0 if a is null - Arithmetic: Perform mathematical operations.
int sum = 5 + 3; int diff = 10 - 2; int prod = 4 * 6; double div = 15 / 3; int rem = 10 % 3; // Remainder of division a++; // Increment b--; // Decrement - Relational: Compare two values and return a boolean.
bool isEqual = (5 == 5); bool isNotEqual = (10 != 5); bool isGreater = (7 > 2); bool isLess = (3 < 8); bool isGreaterOrEqual = (4 >= 4); bool isLessOrEqual = (6 <= 10); - Logical: Perform logical operations on boolean values.
bool andResult = true && false; bool orResult = true || false; bool notResult = !true; - Type testing: Check the type of an object at runtime.
var myObject = "Hello"; bool isString = myObject is String; // Type check bool isInt = myObject is int; String? maybeString; int? result = maybeString as int?; // Type cast (unsafe) - Conditional: Allow code execution based on a condition.
var x = 10; var y = (x > 5) ? "greater than 5" : "less than or equal to 5"; // Ternary operator var z = null; var value = z ?? "default value"; // '??' operator - Cascade operators (..): Allow calling multiple methods or assigning properties of an object in sequence.
var sb = StringBuffer(); sb..write("Hello") ..write(" ") ..write("World!"); - Null-aware access operators (?): Used to prevent errors when working with nullable types.
String? nullableString; int? length = nullableString?.length; // Returns null if nullableString is null - Spread operators (... / ...?): Used to include all elements of a list into another list.
...?is null-safe.var list1 = [1, 2, 3]; var list2 = [0, ...list1, 4]; // [0, 1, 2, 3, 4] var nullableList = null; var list3 = [0, ...?nullableList, 4]; // [0, 4]
The order of operator precedence determines the sequence in which operations are performed in an expression.