When not specifying return type, dart shows exact return type for function inside another, but dynamic for top-level

Viewed 24

VSCode shows String for return type of bar, and dynamic for return type of foo.

void main() {
  bar() => 'bar'; // String bar()
}

foo() => 'foo'; // dynamic bar()
1 Answers

Dart's type inference algorithm differs for top-level declarations and local declarations. That's because top-level declarations can all refer to each other, while local declarations can only refer to earlier local declarations (or to top-level declarations, but those are inferred first, so they're safe at this point).

Because of that, the top-level inference is not as clever as the local type inference, but it's also decidable in reasonable time.

Write types on top-level and class level declarations. It's safer.

Related