In programming, "creating" a variable happens in two distinct steps: Declaration (giving it a name and type) and Initialization (giving it a first value). Understanding this distinction is vital for avoiding null errors in Dart.
1. Variable Declaration
Declaration is simply telling the computer that a variable exists. You specify the type and the name, but you do not give it a value yet. In modern Dart (with Null Safety), declaring a non-nullable variable without a value can lead to errors if you try to use it before assigning one.
Declaring a Variable
1// Declaration ONLY2int age;3String name;4bool isActive;5 6// ⚠️ Note: In modern Dart, you cannot use these variables 7// until they are assigned a value.8// print(age); // ❌ Error: Non-nullable variable 'age' must be assigned before use.HintThink of declaration as reserving a labeled box. The box exists, but it is empty.
2. Variable Initialization
Initialization is the act of assigning a value to a variable for the first time. Once initialized, the variable is ready to be used in your program.
Initializing a Variable
1int score; // Step 1: Declaration2score = 100; // Step 2: Initialization3 4print(score); // ✅ OK: Prints 100HintInitialization puts the first item into the box. You cannot use the contents of the box (the variable) until you put something in it.
3. Combining Declaration and Initialization
Most of the time, developers do both steps in a single line. This is cleaner and safer because it ensures the variable never exists in an uninitialized state.
The All-in-One Approach
1// Declare AND Initialize in one line2int total = 50; 3String city = 'London';4 5// Using 'var' (Type Inference)6// Implicitly declares as String and initializes with 'Hello'7var greeting = 'Hello';HintThis is the preferred standard for most local variables in Dart.
Loot collected
Key takeaways- Declaration = Creating the variable name and type (int x;).
- Initialization = Giving the variable its first value (x = 10;).
- You cannot use a non-nullable variable before it is initialized.
- Combining both steps (int x = 10;) is the safest and most common practice.
Side quests
Practice exercises
Exercise 1: Step-by-Step
First, declare an integer variable named temperature. On the next line, initialize it to 25.
Reveal solutionHide solution
1int temperature;2temperature = 25;Exercise 2: All-in-One
Declare and initialize a String variable named color with the value "Red" in a single line.
Reveal solutionHide solution
1String color = 'Red';Exercise 3: Spot the Error
Why does this code fail? int x; print(x);
Reveal solutionHide solution
1It fails because `x` is declared but not initialized. You cannot use a variable before giving it a value.