---
title: "Declaring Variables in Dart and Letting Inference Pick the Type with var"
date: "2026-12-03T09:51:00+07:00"
description: "Dart's var keyword infers a type from the initializer. Learn how inference works, when Effective Dart wants an explicit annotation, and where it stops."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-var-inference.jpg"
alt: "Conceptual diagram of Dart var declarations with inferred String, int and double type labels attached to variables"
tags: ['dart', 'dart-language', 'type-inference', 'variables', 'null-safety']
---

Writing `var name = 'Bob';` and getting back a fully typed variable is one of Dart's quietest conveniences: the compiler reads the initializer, works out the type, and then enforces it everywhere the variable is used. This post walks through how that inference actually works, when Effective Dart tells you to write the type yourself, and the handful of places where inference genuinely runs out of information.

## How `var` picks a type

Every variable in Dart holds a reference to an object, and its static type is decided once, at compile time. When you write `var name = 'Bob';`, the analyzer reads the initializer, sees a string literal, and records `name` as a `String`. From that line on, assigning an `int` to `name` is a compile-time error rather than a runtime surprise — the type never wobbles, even though you never spelled it out.

```dart
void main() {
  var name = 'Bob';            // String
  var year = 1977;             // int
  var antennaDiameter = 3.7;   // double
  var flybyObjects = ['Jupiter', 'Saturn', 'Uranus']; // List<String>
  var image = {
    'tags': ['saturn'],
    'url': '//path/to/saturn.jpg',
  };                           // Map<String, List<String)>
  print('$name launched in $year.');
  print('${flybyObjects.length} objects, image: ${image['url']}');
}
```

Inference reaches into collections too: the list literal becomes `List<String>` because every element is a string, and the nested map resolves to `Map<String, List<String>>` without a single angle bracket written by hand. The literal types themselves — why `1977` is an `int` and `3.7` a `double` — are covered in `dart-core-types-int-double-bool-string.md`.

## Inference also reads the context

Inference is not only bottom-up from the initializer; it also works top-down from the place the value is used. That is why an integer literal is accepted where a `double` is expected, and why a list literal adopts the element type of the variable it initializes. When a context is present the literal adapts to it; when there is no context, the literal's natural type wins — the mechanism behind conversions like `double z = 1`, which gets its own treatment in `dart-num-int-double-conversion.md`.

```dart
void main() {
  double z = 1;                 // int literal promoted to double: 1.0
  num total = 1;                // num accepts both int and double
  total += 2.5;

  List<int> counts = [1, 2, 3]; // elements checked against int
  print(z + total + counts.first);
}
```

## When Effective Dart tells you to annotate

Inference is the default, but Effective Dart draws clear lines around it. The first rule: **type annotate variables that have no initializer**, because there is nothing for inference to read. Without an annotation such a variable silently becomes `dynamic`, and the analyzer flags it with the `prefer_typing_uninitialized_variables` lint.

```dart
void main() {
  int lineCount; // No initializer: inference has nothing to read.
  if (DateTime.now().hour < 12) {
    lineCount = 0;
  } else {
    lineCount = 42;
  }

  String name = 'Bob';      // Redundant: the initializer says String.
  var nickname = 'Bobby';   // Preferred: name and value carry the type.

  print('$lineCount $name ($nickname)');
}
```

The second rule is the mirror image: **don't redundantly type annotate initialized local variables**. The `omit_local_variable_types` lint exists because `String name = 'Bob';` repeats what the initializer already says, and it buries the variable's interesting parts — its name and value — under a type the reader can predict.

The third rule reaches beyond locals: **annotate fields and top-level variables when the initializer does not make the type obvious**, enforced by `type_annotate_public_apis`. Literals and constructor calls are obvious, but a call to some project-specific factory is not. A signature like `Future<bool> install(PackageId id, String destination)` documents what flows into and out of a library; leaving that boundary to inference would hide it from readers and let an implementation change silently reshape the API.

```dart
const screenWidth = 640;               // Obvious: int.
final timeout = Duration(seconds: 5);  // Obvious: Duration.
```

## When inference picks a type that is too narrow

The subtle failure case is inference succeeding with a type more precise than you intend. It reads the initializer and commits, so a later assignment of a sibling type fails even though the variable was designed to hold either. The fix is to annotate with the type you actually want rather than the type the initializer happens to have — the one situation where Effective Dart explicitly steps aside from its "don't annotate initialized locals" guidance.

```dart
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

void main() {
  var pet = Dog(); // Inferred type: Dog.
  // Error: Cat can't be assigned to Dog.
  pet = Cat();

  Animal anyPet = Dog(); // Annotated wider on purpose.
  anyPet = Cat();
  print('$pet, $anyPet');
}
```

## Object, Object? and dynamic

When a variable is not restricted to a single type, the variables page gives direct advice: say so explicitly. Use `Object` — or `Object?` if null is allowed — and reserve `dynamic` for the rare case where you genuinely want to disable static checking.

```dart
void main() {
  Object name = 'Bob';
  name = 42; // Every value in Dart is an Object.
  print(name);

  Object? maybeName = 'Bob';
  if (maybeName != null) print(maybeName.length); // Promoted to String.

  dynamic looseName = 'Bob';
  print(looseName.length); // No static check happens here.
}
```

`Object` keeps the compiler in the loop: it still forces a null check before dereferencing under null safety, so mistakes surface in the editor. `dynamic` disables static checking entirely — a typo in a member name compiles cleanly and only appears at runtime. Effective Dart puts it plainly: usually you should use `Object` or `Object?` instead. There is a subtler variant of the same problem: when inference has no information at all, it silently fills the gap with `dynamic`, which is exactly what a bare `var parameters;` does.

## Null safety and inference

Nullability is the one thing inference will not decide for you. `var total = 0;` yields a non-nullable `int` because the initializer is non-null, but a variable that may hold null must be declared with `?` and then definitely assigned before it is read.

```dart
void main() {
  int? lineCount; // Nullable: defaults to null.
  lineCount = 42; // Assigned before use...
  print(lineCount); // ...so it is non-null from here on.

  var total = 0; // Inferred int: non-nullable by construction.
  print(total + lineCount);
}
```

Nullable variables are considered initialized because their default value is `null`; non-nullable ones must be definitely assigned before any read, and Dart's flow analysis tracks that through every branch. When analysis cannot prove a variable is set — the normal situation for top-level and instance variables, which initialize lazily — the escape hatch is `late`, not a weaker type.

## Choosing a declaration form

| Declaration | Static type | Reassignable | Reach for it when |
|---|---|---|---|
| `var name = 'Bob';` | `String` (inferred) | Yes | The initializer makes the type obvious — the default for locals |
| `String name = 'Bob';` | `String` | Yes | There is no initializer, or inference picks a type that is too narrow |
| `Object name = 'Bob';` | `Object` | Yes | The value can be several unrelated types but still needs static checks |
| `dynamic name = 'Bob';` | `dynamic` | Yes | You deliberately opt out of static checking |
| `final name = 'Bob';` | `String` (inferred) | No | The variable is assigned exactly once — see `dart-final-vs-const.md` |
| `int? lineCount;` | `int?` | Yes | The value is nullable and assigned later in the flow |

## Takeaways

Inference reads both the initializer and the surrounding context, so `var` gives you a precise static type in nearly every local case, and the compiler keeps enforcing it from declaration onward. When there is no initializer, when the initializer's type is narrower than what you plan to store, or when the declaration is part of a library's public boundary, write the type yourself. Reach for `Object` or `Object?` when a value can be many things but should still be checked, and `dynamic` only when you mean to opt out of checking entirely.

**Takeaway:** Let `var` infer the type of initialized local variables, annotate when there is no initializer or when you need a wider type than inference picks, and reserve `Object?` and `dynamic` for the rare cases where you genuinely don't know or don't care about the type.

## References

- https://dart.dev/language/variables
- https://dart.dev/language
- https://dart.dev/effective-dart/design
- https://dart.dev/effective-dart/usage
