内置值对象的设置器是啥
Posted
技术标签:
【中文标题】内置值对象的设置器是啥【英文标题】:What's the setter of a built_value's object内置值对象的设置器是什么 【发布时间】:2019-01-04 11:52:42 【问题描述】:我正在尝试在flutter中使用built_value,发现如果我声明了一个使用build_value的类型,我通常可以使用点语法为其属性赋值: 我的声明是:
abstract class Post implements Built<Post, PostBuilder>
Post._();
int get userId;
int get id;
String get title;
String get body;
factory Post([updates(PostBuilder b)]) = _$Post;
static Serializer<Post> get serializer => _$postSerializer;
并像这样使用它:
Post p = Post();
p.titie = "hello world";
出现错误:
[dart] 在“Post”类中没有名为“title”的二传手。
我不熟悉 builder
的东西,即使我发现 PostBuilder
具有所有属性的设置器:
PostBuilder().title = '你好世界';
但是我该如何使用呢?
【问题讨论】:
【参考方案1】:BuiltValue 类是不可变的。这是它的主要特点之一。 不变性意味着您不能修改实例。每次修改都必须产生一个新实例。
几种方法之一是
p = (p.toBuilder().titie = 'hello world').build();
获取更新的实例。
或者
p = p.rebuild((b) => b..title = 'hello world');
【讨论】:
谢谢,我也得到了构造方式:Post((b)b.title='hello';return b;); 是的,这也可以,但是如果您有更多属性并且只想更改其中一个,您仍然需要重复所有其他属性。【参考方案2】:其实有一个full example 单独有源代码。
// Values must be created with all required fields.
final value = new SimpleValue((b) => b..anInt = 3);
// Nullable fields will default to null if not set.
final value2 = new SimpleValue((b) => b
..anInt = 3
..aString = 'three');
// All values implement operator==, hashCode and toString.
assert(value != value2);
// Values based on existing values are created via "rebuild".
final value3 = value.rebuild((b) => b..aString = 'three');
assert(value2 == value3);
// Or, you can convert to a builder and hold the builder for a while.
final builder = value3.toBuilder();
builder.anInt = 4;
final value4 = builder.build();
assert(value3 != value4);
【讨论】:
以上是关于内置值对象的设置器是啥的主要内容,如果未能解决你的问题,请参考以下文章