Dart factory constructors with / without keyword `

2019-07-31 16:40发布

问题:

I came across the following code example from flutter_redux example code. Had a hard time to understand why factory SearchState.initial() returns with a new keyword while factory SearchState.loading() and factory SearchState.error() don't.

class SearchState {
  final SearchResult result;
  final bool hasError;
  final bool isLoading;

  SearchState({
    this.result,
    this.hasError = false,
    this.isLoading = false,
  });

  factory SearchState.initial() =>
      new SearchState(result: SearchResult.noTerm());

  factory SearchState.loading() => SearchState(isLoading: true);

  factory SearchState.error() => SearchState(hasError: true);
}

Just found the Dart language tour not very helpful to this case, and the Dart language specification is too obscure.

回答1:

Quotes from the effective dart guide:

Dart 2 makes the new keyword optional. Even in Dart 1, its meaning was never clear because factory constructors mean a new invocation may still not actually return a new object.

The language still permits new in order to make migration less painful, but consider it deprecated and remove it from your code.



回答2:

There is no difference. In Dart 2, the new keyword was made optional. If you don't write anything when calling a constructor, it's implicitly assumed to be new.

Most code still uses new because it was required in Dart 1, and some people even prefer it, so you will see code both with and without new.



标签: dart