Variables
6 min · Dart
Store values in named boxes called variables.
Enemy 1 of 5
var and type inference
A variable is a named container that holds a value so you can refer to it later without retyping it. In Dart, the simplest way to create one is with var name = value; — var doesn't mean "no type," it means "figure out the type from the value I'm assigning." This process is called type inference: Dart looks at 'Ada' being a piece of text and locks the variable name in as a String from that point on.
This is a middle ground between two extremes you'll find in other languages: PHP and Ruby don't require you to think about types explicitly at all, while languages like Java or C traditionally require you to spell out the type yourself, like String name = 'Ada';. Dart lets you write the short var form, but it's still enforcing a real, fixed type behind the scenes — once name is inferred as a String, trying to later assign name = 5; (a number) is a compile-time error, not something Dart quietly allows.
You can also be fully explicit if you prefer or if it makes the code clearer to a reader: String name = 'Ada'; and var name = 'Ada'; produce the exact same behavior. Many Dart style guides recommend var for local variables when the type is obvious from the right-hand side, and an explicit type when it helps readability.
Loading editor...