Syntax Cheat Sheet: Variables and Types
Dart's three variable declarations cover every mutability need: var name = 'Ann' infers the type and allows reassignment, final age = 30 is assigned once at runtime and cannot be reassigned, and const pi = 3.14 must be a compile-time constant. Core built-in types are int, double (both subtypes of num), String (with triple-quoted multi-line and ${} interpolation support), bool, and the collection types List<T>, Set<T>, and Map<K, V>, all of which are generic and, since Dart 3, can also be constructed as immutable literals when marked const.
Cricket analogy: var, final, and const map to a squad announced fresh before every match, var, a playing XI locked once the toss happens, final, and a captain named permanently for the whole series before a ball is bowled, const.
Control Flow and Functions
Dart supports the usual if/else, for, for-in, while, and do-while, plus a switch statement that, since Dart 3, supports pattern matching and exhaustiveness checking on sealed classes and enums. Functions support positional parameters, named parameters ({required String name, int age = 0}), and optional positional parameters ([int? extra]), plus arrow syntax for single-expression bodies (int square(int x) => x * x) and can themselves be assigned to variables or passed around, since functions are first-class objects in Dart.
Cricket analogy: Named parameters with required and defaults are like a scorecard entry that mandates batsman name but defaults how out to not out unless specified, structured input with sensible fallbacks.
Collections at a Glance
List, Set, and Map literals share a unified syntax for building collections inline: [1, 2, 3] for a List, {1, 2, 3} for a Set (uniqueness enforced), and {'a': 1, 'b': 2} for a Map; inside any of these, if and for can appear directly in the literal ([if (showExtra) extra, ...otherItems]) to conditionally include or spread elements without a separate builder step. Common operations to know cold: .map() transforms each element lazily (returns an Iterable, call .toList() to materialize), .where() filters, .fold() reduces to a single value with a starting accumulator, and .expand() flattens nested iterables, all of which avoid manual index-based loops.
Cricket analogy: A Set enforcing uniqueness is like a squad list that automatically rejects a duplicate player entry, no one can be selected twice for the same match no matter how many times you try to add them.
// Variables
var city = 'Delhi'; // type inferred, reassignable
final year = 2026; // set once at runtime
const pi = 3.14159; // compile-time constant
// Null safety
String? nickname;
print(nickname?.toUpperCase() ?? 'NO NICKNAME');
nickname ??= 'Ace';
// Collections
final scores = [90, 85, if (true) 100]; // collection-if
final passed = scores.where((s) => s >= 80).toList();
final total = scores.fold(0, (sum, s) => sum + s);
// Functions
int square(int x) => x * x;
void greet({required String name, String greeting = 'Hello'}) {
print('$greeting, $name!');
}Null Safety Operators
The core null-safety operators to have memorized: ? marks a type nullable (String? name), ?. safely accesses a member only if the receiver isn't null (returns null otherwise instead of throwing), ?? provides a fallback value if the left side is null (name ?? 'Guest'), ??= assigns only if the variable is currently null (count ??= 0), and ! is the null assertion operator that tells the analyzer 'trust me, this isn't null here' — but throws a runtime exception immediately if you're wrong, so it should be reserved for cases you've already proven safe rather than used as a blanket way to silence the analyzer.
Cricket analogy: The ! null assertion operator is like a captain reviewing a DRS decision with total confidence it'll go their way, if they're wrong, the review is burned immediately and there's no recovering it mid-over.
Keep this reference alongside dart-best-practices and dart-interview-questions — the syntax here is exactly what shows up in real interview whiteboard exercises and day-to-day code review comments.
The ! null assertion operator is not a substitute for actually checking for null — using it defensively everywhere just moves potential crashes from compile time to runtime, defeating the purpose of sound null safety.
- var infers type and is reassignable; final is set once at runtime; const must be a compile-time constant.
- Core types: int, double (both num), String (supports ${} interpolation), bool, List<T>, Set<T>, Map<K,V>.
- Named parameters use {required String name, int age = 0}; optional positional use [int? extra]; arrow syntax for one-line bodies.
- Since Dart 3, switch supports pattern matching and exhaustiveness checking on sealed classes and enums.
- Collection-if/collection-for and the spread operator (...) build lists/sets/maps inline without manual loops.
- .map()/.where()/.fold()/.expand() are the core functional collection operations, replacing manual index-based loops.
- Null-safety operators: ?, ?., ??, ??=, and ! (null assertion — throws immediately if wrong).
Practice what you learned
1. What's the key difference between final and const?
2. What does the ?? operator do?
3. What does .map() return before calling .toList()?
4. Which loop construct is guaranteed to execute its body at least once?
5. What happens if you use ! on a variable that turns out to be null at that point?
Was this page helpful?
You May Also Like
Dart Best Practices
A working guide to idiomatic Dart: naming, null safety, collections, async patterns, and tooling that keeps a Dart codebase clean and fast.
Dart Interview Questions
The core Dart concepts interviewers actually probe — null safety, async programming, OOP/mixins, and Flutter-adjacent performance details.
Dart vs Kotlin
A practical comparison of Dart and Kotlin across compilation, null safety, concurrency, and ecosystem so you can pick the right tool for a given project.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics