gpt4 book ai didi

dart - 带有/不带有关键字 `new`的Dart工厂构造函数,有什么区别?

转载 作者:行者123 更新时间:2023-12-03 03:08:14 26 4
gpt4 key购买 nike

我从flutter_redux示例代码中遇到了以下代码示例。很难理解为什么factory SearchState.initial()new关键字返回而factory SearchState.loading()factory SearchState.error()没有返回。

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);
}

刚刚发现Dart语言之旅对这种情况不是很有帮助,而且Dart语言规范过于晦涩。

最佳答案

effective dart指南中的引语:

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.

关于dart - 带有/不带有关键字 `new`的Dart工厂构造函数,有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com