← Dart EnglishChapter 02 of 13

Variables and Types

## Learning Objectives - Declare and initialize variables - Understand Dart's type system - Master type inference - Work with final and const ## Variables ### Declaration ```dart var name = 'Alice'; // Type inferred String greeting = 'Hello'; // Explicit type name = 'Bob'; // Reassignment allowed // greeting = 123; // Error: type mismatch ``` ### Naming Rules - Start with letter or underscore - Can contain numbers (after first character) - Case-sensitive - Cannot use reserved words ```dart var age = 25; // Valid var _count = 0; // Valid var price2 = 10.99; // Valid // var 2ndPlace = 1; // Invalid: starts with number // var class = 'test'; // Invalid: reserved word ``` ## Type Inference ### var Keyword ```dart var city = 'Paris'; // Inferred as String var population = 2100000; // Inferred as int var area = 105.4; // Inferred as double var isCapital = true; // Inferred as bool // city = 123; // Error: can't assign int to String ``` ### Final and Const ```dart final name = 'Alice'; // Set once, inferred as String // name = 'Bob'; // Error: final can't be reassigned const pi = 3.14159; // Compile-time constant const maxItems = 100; // Compile-time constant ``` ### Difference Between final and const ```dart final now = DateTime.now(); // OK: evaluated at runtime // const now = DateTime.now(); // Error: const must be compile-time ``` ## Built-in Types ### Numbers ```dart void main() { // int: whole numbers int count = 42; int hex = 0xFF; // double: floating-point double price = 19.99; double scientific = 1.5e10; print('Count: $count, Price: $price'); } ``` ### Strings ```dart void main() { String single = 'Single quotes'; String double = "Double quotes"; String multiLine = ''' This is a multi-line string '''; print(single); print(double); } ``` ### Booleans ```dart void main() { bool isActive = true; bool isComplete = false; // Boolean operators print(isActive && !isComplete); // true print(isActive || isComplete); // true print(!isActive); // false } ``` ### Lists ```dart void main() { // List - ordered collection List numbers = [1, 2, 3, 4, 5]; var names = ['Alice', 'Bob', 'Charlie']; print(numbers.length); // 5 print(names[0]); // Alice print(names.contains('Bob')); // true } ``` ### Sets ```dart void main() { // Set - unordered collection of unique items Set fruits = {'apple', 'banana', 'orange'}; var colors = {'red', 'green', 'blue'}; print(fruits.contains('banana')); // true fruits.add('grape'); print(fruits.length); // 4 } ``` ### Maps ```dart void main() { // Map - key-value pairs Map ages = {'Alice': 30, 'Bob': 25}; var scores = {'Math': 95, 'Science': 88}; print(ages['Alice']); // 30 print(scores.containsKey('Math')); // true ages['Charlie'] = 35; } ``` ### Runes ```dart void main() { // Runes - Unicode code points String emoji = 'Hello 👋'; print(emoji.runes.toList()); // [72, 101, 108, ...] // String interpolation with unicode print('Heart: \u2665'); // Heart: ♥ print('Euro: \u20AC'); // Euro: € } ``` ## Type Conversion ### Number to String ```dart void main() { int age = 30; double price = 19.99; String ageStr = age.toString(); String priceStr = price.toString(); String priceFixed = price.toStringAsFixed(2); // "19.99" } ``` ### String to Number ```dart void main() { String numStr = '42'; String decimalStr = '3.14'; int num = int.parse(numStr); // 42 double dec = double.parse(decimalStr); // 3.14 // With error handling try { int invalid = int.parse('abc'); } catch (e) { print('Invalid number format'); } } ``` ### TryParse (Safer) ```dart void main() { int? result = int.tryParse('123'); print(result); // 123 int? invalid = int.tryParse('abc'); print(invalid); // null } ``` ## Dynamic Type ```dart void main() { dynamic value = 'text'; print(value); // text value = 123; print(value); // 123 // Avoid using dynamic when possible // loses type checking benefits } ``` ## Type Alias ```dart typedef IntList = List; typedef StringMap = Map; void main() { IntList numbers = [1, 2, 3]; StringMap names = {'first': 'Alice', 'second': 'Bob'}; } ``` ## Summary - Variables store data values - `var` lets Dart infer type; explicit types also supported - `final` for runtime constants (set once) - `const` for compile-time constants - Built-in types: int, double, String, bool, List, Set, Map, Runes - Use `tryParse` for safe string-to-number conversion - Prefer strong typing over `dynamic`

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →