6

我正在尝试在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 = 'hello world'; 但我该如何使用它?

4

2 回答 2

10

BuiltValue 类是不可变的。这是它的主要特点之一。
不变性意味着您不能修改实例。每次修改都必须产生一个新实例。

几种方法之一是

p = (p.toBuilder().titie = 'hello world').build();

获取更新的实例。

或者

p = p.rebuild((b) => b..title = 'hello world');
于 2018-07-27T11:09:47.647 回答
1

事实上,仅源代码就有一个完整的示例。

// 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);
于 2018-07-30T10:10:41.403 回答