Dart Type Inference
Let Dart automatically determine variable types
🔍 What is Type Inference?
Type inference allows Dart to automatically determine variable types from their values. Use 'var', 'final', or 'const' keywords to let Dart figure out types.
// Dart infers the type automatically
var name = 'Alice'; // String
var age = 25; // int
var height = 5.9; // double
Type Inference Keywords
var
Mutable variables with inferred type
var count = 10;
count = 20; // Can change
final
Immutable variables set at runtime
final time = DateTime.now();
// time = something; // Error!
const
Compile-time constants
const pi = 3.14159;
const greeting = 'Hello';
Explicit Types
Manually specify types
String name = 'Bob';
int score = 95;
🔹 Using var Keyword
Let Dart infer types for mutable variables:
// Dart automatically determines types
var message = 'Hello World'; // String
var count = 42; // int
var price = 19.99; // double
var isActive = true; // bool
var items = ['apple', 'banana']; // List
// You can change values but not types
count = 100; // OK - still int
// count = 'text'; // Error - can't change type
Output:
message: Hello World (String)
count: 100 (int)
price: 19.99 (double)
🔹 Using final Keyword
Create immutable variables with inferred types:
// Set once, can't change later
final userName = 'alice123';
final currentTime = DateTime.now();
final randomNumber = 42;
print('User: $userName');
print('Time: $currentTime');
// This would cause an error:
// userName = 'bob456'; // Error!
Output:
User: alice123
Time: 2024-01-15 10:30:45.123
🔹 Using const Keyword
Create compile-time constants:
// Known at compile time
const appName = 'My Dart App';
const version = 1.0;
const maxUsers = 1000;
const features = ['login', 'dashboard', 'settings'];
// Mathematical expressions
const area = 3.14 * 5 * 5; // Calculated at compile time
print('$appName v$version');
print('Max users: $maxUsers');
Output:
My Dart App v1.0
Max users: 1000
🔹 When to Use Each
Choose the right keyword for your needs:
Use var when:
- Variable value will change
- Type is obvious from the value
- You want cleaner, shorter code
Use final when:
- Value is set once and never changes
- Value is determined at runtime
- You want to prevent accidental changes
Use const when:
- Value is known at compile time
- Creating truly immutable objects
- Performance optimization is important
// Examples of when to use each
var counter = 0; // Will change
final userId = getUserId(); // Set once at runtime
const appTitle = 'My App'; // Never changes, known at compile time