Introduction
Variables are containers that store data values in your program. In Dart, you can use thevar keyword for type inference, where Dart automatically determines the variable’s type based on the value assigned to it.
Declaring Variables with var
Dart uses type inference when you declare variables withvar. The compiler automatically determines the type based on the initial value:
Variable Naming Best Practices
Good Variable Names ✓
Variable names should be:- Descriptive: Clearly indicate what the variable stores
- Complete: Use full words, avoid abbreviations
- Lowercase: Start with a lowercase letter
- CamelCase: Use camelCase for multi-word names
Bad Variable Names ✗
Why Good Naming Matters
Readability
Code is read more often than it’s written. Descriptive names make your code self-documenting.
Maintainability
Clear names make it easier to update and debug your code months or years later.
Collaboration
Other developers (and future you) will understand your code without extensive comments.
Fewer Bugs
Descriptive names help prevent mistakes and make errors easier to spot.
Naming Convention Rules
Variable Names
Variable Names
- Start with a lowercase letter
- Use camelCase for multiple words:
firstName,userAge,isActive - Can contain letters, numbers, and underscores
- Cannot start with a number
- Cannot use Dart reserved keywords
Complete Example
Here’s a comparison showing the difference between good and bad variable naming:Key Takeaways
- Use
varfor type inference when the type is obvious from the assigned value - Always use descriptive, complete variable names
- Follow camelCase naming convention
- Avoid single letters, abbreviations, and numbered suffixes like
num1,num2 - Write code that reads like natural language