带有/不带有关键字`new`的Dart工厂构造函数,有什么区别? [英] Dart factory constructors with / without keyword `new`, what's the difference?

查看:39
本文介绍了带有/不带有关键字`new`的Dart工厂构造函数,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 flutter_redux 示例代码.很难理解为什么 factory SearchState.initial()返回 new 关键字,而 factory SearchState.loading()不需要工厂SearchState.error().

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

只是发现Dart语言之旅对这种情况不是很有帮助,而且Dart语言规范太晦涩.

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

推荐答案

Dart 2使new关键字为可选.即使在Dart 1中,其含义也是永远不清楚,因为工厂构造函数意味着可能会进行新的调用仍然没有真正返回新对象.

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.

这篇关于带有/不带有关键字`new`的Dart工厂构造函数,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆