繁体   English   中英

Dart/Flutter 删除命名构造函数中的样板参数以减少代码大小

[英]Dart/Flutter remove boilerplate parameters in named constructor to reduce code size

我有一个带有多个命名构造函数的 class。 它们都有一组已定义的参数,现在我必须在添加新的命名构造函数时重新重写它们。

有没有办法减少下面代码的样板文件,不再重新输入所有参数?

class Person {
  final String name;
  final String lastName;
  final String login;
  final String anotherValue;
  final String address;
  final int age;
  final String _text;

  const Person.sayHello(
    this.name,
    this.age,
    this.lastName,
    this.login,
    this.anotherValue,
    this.address,
  ) : _text = "Hello";

  const Person.sayBye(
    this.name,
    this.age,
    this.lastName,
    this.login,
    this.anotherValue,
    this.address,
  ) : _text = "Bye";
  
  void readText() {
    debugPrint(_text);
  }
}

我尝试使用抽象或扩展方法,但找不到合适的方法。

这可能不是你想要的,但我们可以像这样划分有关命名构造函数的代码。

class Person {
  const Person(
    this.name,
    this.age,
    this.lastName,
    this.login,
    this.anotherValue,
    this.address,
    this._personText,
  );

  final String name;
  final String lastName;
  final String login;
  final String anotherValue;
  final String address;
  final int age;
  final PersonText _personText;

  void readText() {
    debugPrint(_personText.text);
  }
}

class PersonText {
  const PersonText.sayHello() : text = 'Hello';
  const PersonText.sayBye() : text = 'Bye';

  final String text;
}

你也可以这样替换它。

enum PersonText {
  hello,
  bye,
}

extension PersonTextHelper on PersonText {
  String get text {
    switch (this) {
      case PersonText.hello:
        return 'Hello';
      case PersonText.bye:
        return 'Bye';
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM