Dart Literals

Fixed values in Dart code

πŸ’Ž What are Dart Literals?

Literals in Dart are fixed values written directly in your code. They represent actual data like numbers, strings, booleans, and collections that don't change during compilation.


// Literal examples
int age = 25;        // Number literal
String name = 'Bob'; // String literal
bool isActive = true; // Boolean literal
                                    

Types of Literals

πŸ”’

Number Literals

Integer and double values

int count = 42;
double price = 19.99;
πŸ“

String Literals

Text values in quotes

String message = 'Hello';
String text = "World";
βœ…

Boolean Literals

True or false values

bool isReady = true;
bool isComplete = false;
πŸ“‹

Collection Literals

Lists, sets, and maps

List numbers = [1, 2, 3];
Map person = {'name': 'Alice'};

πŸ”Ή Number Literals

Different ways to write numeric values:

// Integer literals
int decimal = 42;
int hexadecimal = 0x2A;        // 42 in hex
int binary = 0b101010;         // 42 in binary
int octal = 0o52;              // 42 in octal

// Double literals
double simple = 3.14;
double scientific = 1.23e4;    // 12300.0
double negative = -45.67;

// Large numbers with underscores for readability
int million = 1_000_000;
double precise = 3.141_592_653;

print('Decimal: $decimal');
print('Hex: $hexadecimal');
print('Binary: $binary');
print('Scientific: $scientific');
print('Million: $million');

Output:

Decimal: 42
Hex: 42
Binary: 42
Scientific: 12300.0
Million: 1000000

πŸ”Ή String Literals

Various ways to create string literals:

// Single and double quotes
String single = 'Hello World';
String double = "Hello World";

// Multi-line strings
String multiLine = '''
This is a
multi-line
string literal
''';

// Raw strings (no escape sequences)
String rawString = r'This is a raw string with \n and \t';

// String with escape sequences
String escaped = 'Line 1\nLine 2\tTabbed text';

// Unicode characters
String unicode = 'Dart is fun! 🎯';

print('Single: $single');
print('Multi-line: $multiLine');
print('Raw: $rawString');
print('Escaped: $escaped');
print('Unicode: $unicode');

Output:

Single: Hello World
Multi-line:
This is a
multi-line
string literal

Raw: This is a raw string with \n and \t
Escaped: Line 1
Line 2Β Β Β Β Tabbed text
Unicode: Dart is fun! 🎯

πŸ”Ή Collection Literals

Creating collections with literal syntax:

// List literals
List<int> numbers = [1, 2, 3, 4, 5];
List<String> fruits = ['apple', 'banana', 'orange'];
List<dynamic> mixed = [1, 'hello', true, 3.14];

// Set literals
Set<String> colors = {'red', 'green', 'blue'};
Set<int> uniqueNumbers = {1, 2, 3, 2, 1}; // Duplicates removed

// Map literals
Map<String, int> ages = {
  'Alice': 25,
  'Bob': 30,
  'Charlie': 35
};

Map<String, dynamic> person = {
  'name': 'John',
  'age': 28,
  'isStudent': false,
  'grades': [85, 90, 78]
};

print('Numbers: $numbers');
print('Colors: $colors');
print('Unique numbers: $uniqueNumbers');
print('Ages: $ages');
print('Person: $person');

Output:

Numbers: [1, 2, 3, 4, 5]
Colors: {red, green, blue}
Unique numbers: {1, 2, 3}
Ages: {Alice: 25, Bob: 30, Charlie: 35}
Person: {name: John, age: 28, isStudent: false, grades: [85, 90, 78]}

πŸ”Ή Special Literals

Special literal values in Dart:

// Null literal
String? nullableString = null;
int? nullableInt = null;

// Symbol literals
Symbol symbol1 = #mySymbol;
Symbol symbol2 = Symbol('anotherSymbol');

// Rune literals (Unicode code points)
Runes heart = Runes('\u2665');  // β™₯
Runes smiley = Runes('\u{1f600}'); // πŸ˜€

// Empty collections
List<String> emptyList = [];
Set<int> emptySet = <int>{};
Map<String, int> emptyMap = {};

print('Null string: $nullableString');
print('Symbol: $symbol1');
print('Heart: ${String.fromCharCodes(heart)}');
print('Smiley: ${String.fromCharCodes(smiley)}');
print('Empty list: $emptyList');
print('Empty set: $emptySet');
print('Empty map: $emptyMap');

Output:

Null string: null
Symbol: Symbol("mySymbol")
Heart: β™₯
Smiley: πŸ˜€
Empty list: []
Empty set: {}
Empty map: {}

πŸ”Ή Literal Best Practices

Tips for using literals effectively:

Performance Tips:

  • Use const: Make literals const when possible for better performance
  • Type annotations: Specify types for better optimization
  • Avoid large literals: Consider loading large data from files

Readability Tips:

  • Use underscores: Make large numbers readable (1_000_000)
  • Multi-line strings: Use triple quotes for long text
  • Meaningful names: Assign literals to well-named variables
// Good practices
const int maxUsers = 1_000_000;
const List<String> supportedFormats = ['jpg', 'png', 'gif'];
const Map<String, String> errorMessages = {
  'network': 'Network connection failed',
  'timeout': 'Request timed out',
  'invalid': 'Invalid input provided'
};

// Using the constants
print('Max users: $maxUsers');
print('Supported: $supportedFormats');
print('Error: ${errorMessages['network']}');

Output:

Max users: 1000000
Supported: [jpg, png, gif]
Error: Network connection failed

🧠 Test Your Knowledge

Which of these is a valid hexadecimal literal in Dart?