Skip to main content

Introduction

Variables are containers that store data values in your program. In Dart, you can use the var 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 with var. The compiler automatically determines the type based on the initial value:

Variable Naming Best Practices

Following proper naming conventions is crucial for writing clean, maintainable code.

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 ✗

Avoid these naming patterns - they make your code hard to read and maintain:

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

  • 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:
When choosing variable names, ask yourself: “Will I understand what this variable represents if I read this code in 6 months?”

Key Takeaways

  • Use var for 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

Next Steps

Now that you understand how to declare and name variables, let’s explore the different data types available in Dart.