google / google/built_value.dart

Question: How to reference a parent node from a child node.

Open
#1,212 5 comments 0 reactions 1 assignee Claimed by @davidmorgan View on GitHub
question
Dominant language
Dart
Stars
886
Forks
195
Avg merge
1d 11h
Merged PRs (30d)
4

Description

If I have a list of child nodes, I can simply call this list from the parent object.

The child node, on the other hand, has no reference to the parent node. In a deeply nested data model, however, a reference from child nodes to the parent node would be extremely convenient. For example, a Flutter widget could have only one child node passed to it for display. However, it might be necessary to retrieve or change information about the fathers. Without the reference to the father, the entire chain from the leaf node to the root node would have to be passed to the widget for this.

Value types, of course, cannot store references, only values.
The only idea I can think of is to leave the model as it is:

```dart
part 'model.g.dart';

@SerializersFor([Person])
final Serializers serializers = (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

abstract class Person implements Built {
String get name;
BuiltSet get children;

Person._();
factory Person([void Function(PersonBuilder) updates]) = _$Person;

static Serializer get serializer => _$personSerializer;
}
```

The reference of the parent node in the child node, on the other hand, could be stored in a ViewModel. Here as a global map as a static field of the extension class `GetParent` and a getter `parent` as an extension method for easier calling.

```dart
extension GetParent on Person {
static Map childToParent = {};

Person get parent {
final parent = childToParent[this];
if (parent != null) {
return parent;
} else {
throw StateError("A child should always have the parent in the childToParent Map");
}
}
}
```

Then the getter `parent` could simply be called on the child node.

```dart
void main() {
test('link from child to parent works', () {
final arthas = Person((cb) => cb.name = "Arthas");

final terenas = Person((b) => b
..name = "Terenas"
..children = SetBuilder([arthas]));

GetParent.childToParent.putIfAbsent(arthas, () => terenas);

expect(arthas.parent, terenas);
});
}
```

However, the `childToParent` map must also be filled manually for this. It would be nicer if the child node could be automatically linked to the father node while the father is being created.

Is there a better way to implement this in `built_value`?

Are there best practices on how to add such references in a ViewModel without changing the model?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.