Conditional Operator
Part of the Fundamentals section of Coddy's Dart journey — lesson 30 of 94.
The conditional operator (?:) provides a concise way to write if-else statements in one line:
condition ? expressionIfTrue : expressionIfFalseExample:
void main() {
int age = 20;
String status = age >= 18 ? 'Adult' : 'Minor';
print(status);
}Output: Adult
It works with different data types and is ideal for simple conditional assignments.
Challenge
EasyCreate a program that uses the conditional operator (?:) to determine if a player has enough points to level up in a game:
- Declare an integer variable
playerScorewith a value of 750 - Declare an integer variable
levelUpThresholdwith a value of 500 - Use the conditional operator to create a string message that says either:
- "Level up!" if the player's score is greater than or equal to the threshold
- "Keep trying!" if the player's score is less than the threshold
- Store this message in a string variable called
message - Print the player's score with the format:
Player score: 750 - Print the message
- Update the player's score to 450
- Use the conditional operator again to update the message based on the new score
- Print the updated player's score with the format:
Player score: 450 - Print the updated message
Your output should match the expected format exactly.
Cheat sheet
The conditional operator (?:) provides a concise way to write if-else statements in one line:
condition ? expressionIfTrue : expressionIfFalseExample:
int age = 20;
String status = age >= 18 ? 'Adult' : 'Minor';It works with different data types and is ideal for simple conditional assignments.
Try it yourself
void main() {
// Declare your variables here
int playerScore = _;
int levelUpThreshold = _;
// Use conditional operator to create the first message
String message = playerScore >= levelUpThreshold ? _ : _;
// Print player score and message
print("Player score: $playerScore");
print(message);
// Update player score
playerScore = _;
// Use conditional operator to update the message
message = playerScore >= levelUpThreshold ? _ : _;
// Print updated player score and message
print("Player score: $playerScore");
print(message);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Comparison OperatorsLogical ANDLogical ORLogical NOTType Test OperatorsRecap - Making Comparisons7Working with Strings
String ConcatenationString InterpolationMulti-line StringsString PropertiesBasic String Methods10Collections - Maps Basics
What are Maps?Creating a MapAccessing Values by KeyKey-Value PairsGetting Map SizeGetting KeysGetting ValuesChecking if a Key Exists13Null Safety In Depth
Understanding NullNullable TypesNon-Nullable TypesNull Assertion OperatorLate InitializationRecap - Handling Null Safely16Fundamentals Challenges
Challenge: List of calculationChallenge: Sum of numbersChallenge: Find product2Variables and Basic Data Types
What are Variables?StringsIntegers (int)Doubles (double)Booleans (bool)Type Inference with 'var'Final VariablesConstant VariablesNaming ConventionsBasic Null SafetyRecap - Declaring Variables8Control Flow - Loops
The 'for' LoopThe 'while' LoopThe 'do-while' LoopUsing 'break' in LoopsUsing 'continue' in LoopsRecap - Repeating Code3Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorIncrement and DecrementAssignment ShortcutsRecap - Simple Calculations6Control Flow - Decision Making
The 'if' StatementThe 'else' StatementThe 'else if' StatementRecap - Simple DecisionsNested 'if' StatementsThe 'switch' Statement9Collections - Lists Basics
What are Lists?Creating a ListAccessing by IndexGetting List LengthAdding ElementsRemoving ElementsChecking if a List is EmptyIterating Over a List12Functions Advanced
Optional Positional ParametersNamed ParametersRequired Named ParametersDefault Parameter ValuesRecap - Function Parameters15Project: Simple Calculator
Setting UpDeclaring Number