Home > OS >  When not specifying return type, dart shows exact return type for function inside another, but dynam
When not specifying return type, dart shows exact return type for function inside another, but dynam

Time:06-18

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()

CodePudding user response:

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.

  •  Tags:  
  • dart
  • Related