Variables, Constants and Types
3.1 Declaring Variables
Local variables (inferred type) Values known at runtime that don't change Compile time
Literal constants, canonicalized objects Lazily / later Deferred initialization (non-nullable)
var name = 'Bob'; // type inferred as String (can't later assign an int)
String city = 'Pune'; // explicit type
int age = 30;
double height = 1.75;
bool isActive = true;
final createdAt = DateTime.now(); // runtime constant: assigned once
const pi = 3.14159; // compile-time constant
const List<int> primes = [2, 3, 5]; // deeply immutable constant collection
dynamic anything = 42; // disables static checking (avoid)
anything = 'now a string';
Object obj = 'any non-null value'; // a safe "any" (needs casts to use specific members)3.2 Built-in Types
Integers (64-bit on native, JS number semantics on the web) 64-bit floating point Supertype of int and double UTF-16 text (immutable) true / false List<T>, Set<T>, Map<K, V>
Anonymous, immutable aggregates (1, 'a') (Dart 3) Runes / String.runes Unicode code points #symbolName (reflection/metadata) The type of null Object / Object? Root of non-nullable / all types Turns off static checking No meaningful value
Expressions that never complete (always throw) Function, Future<T>, Stream<T>, Iterable<T> Common library types
3.3 Type Inference, Checks and Conversion
var count = 10;
print(count.runtimeType); // int
if (count is int) print('integer');
num n = 5;
int i = n as int; // cast (throws TypeError if wrong)
int parsed = int.parse('42');
int? maybe = int.tryParse('abc'); // null instead of throwing
double d = double.parse('3.14');
String s = 42.toString();
String fixed = 3.14159.toStringAsFixed(2); // "3.14"
int truncated = 9.99.toInt(); // 9
int rounded = 9.5.round(); // 10
double asDouble = 5.toDouble();3.4 late Variables
Reading an uninitialized late variable throws a LateInitializationError.
late final String config; // assigned before use (checked at runtime)
void init() => config = loadConfig();
late final heavy = computeExpensive(); // lazy initialization: runs on first access
class Widget {
late final Controller controller; // initialized in an init method rather than the constructor
}3.5 Wildcard Variables (Dart 3.7)
for (var _ in List.filled(3, 0)) print('hi');
void callback(int _, String _) {} // multiple `_` parameters don't clash (non-binding wildcards)
var (_, second) = (1, 2);