As a complete beginner learning Dart, I want to understand if the void type is required for a main function. In the official language tour: https://dart.dev/guides/language/language-tour#a-basic-dart-program the examples do not include the void keyword/type. But in other places we seed void main() { ...

The following two snippets of code have the same output:

main() {
  print('Hello World!');
}

Runs fine on Dart Pad: https://dartpad.dartlang.org/fa6f6e5a7b9406e88b31a17e82655ef8
(we don't see any compiler warnings or advice suggesting the void should be added)

void main() {
  print('Hello World!');
}

Is the void a convention that nobody questions or can we exclude it without any consequences?

Note: I'm aware of the history of void keyword/type, I just want to understand if I can safely omit the void from more advanced programs or if it's required.


Solution 1: Benedikt J Schlegel

Declaring no type is identical to declaring void.

I'm not sure if Flutter/Dart want the void there for some sort of "identification" but I doubt it. If it runs, it should be 100% the same.


Solution 2: jamesdlin

The Dart 2.2 language specification says:

18.4 Scripts

A script is a library whose exported namespace (18.2) includes a top-level function declaration named main that has either zero, one or two required arguments.

The spec imposes requirements on the name and the arity (and types) of its arguments. There is no requirement on its return type, so using a different type (such as dynamic, which is what it would be if you omit void) would have no effect.


Solution 3: David Miguel

The Dart linter has the following rule:

always_declare_return_types (ref)

DO declare method return types.

When declaring a method or function always specify a return type. Declaring return types for functions helps improve your codebase by allowing the analyzer to more adequately check your code for errors that could occur during runtime.

BAD:

main() { }

_bar() => _Foo();

class _Foo {
  _foo() => 42;
}

GOOD:

void main() { }

_Foo _bar() => _Foo();

class _Foo {
  int _foo() => 42;
}