Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
AlexanderJohr opened this issue Jan 22, 2023 · 5 comments
Open

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

AlexanderJohr opened this issue Jan 22, 2023 · 5 comments
Assignees
Labels

Comments

@AlexanderJohr
Copy link

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:

part 'model.g.dart';

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

abstract class Person implements Built<Person, PersonBuilder> {
  String get name;
  BuiltSet<Person> get children;

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

  static Serializer<Person> 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.

extension GetParent on Person {
  static Map<Person, Person> 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.

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?

@davidmorgan davidmorgan self-assigned this Jan 23, 2023
@davidmorgan
Copy link
Collaborator

Thanks Alex.

I don't have suggestions for a good way to achieve this in Flutter; but what you're describing sounds along the right lines.

When I've done this in my own code--but not Flutter code--I've done it by adding IDs to the data classes, then having a global map from ID to instance. I've used a type Id<T> that does the lookup.

Maybe there is something already in Flutter that gives you an ID to instance mapping you could use.

Or, perhaps you could use the finalizeBuilder hook to maintain such a mapping. It gets calls just before a builder is called. It doesn't give you the final instance, but you can get that by calling build on the builder. (You'll need to guard the hook with a boolean check so that it's not already running, so it doesn't trigger itself).

@AlexanderJohr
Copy link
Author

Thanks for clarifying!

Do you have an example of the Id<T> lookup approach?

@davidmorgan
Copy link
Collaborator

Nothing I can point to unfortunately. The idea is similar to your example, except:

  • Add type Id<T> which holds a numerical ID and has method T value that looks up the ID in a global map
  • Data classes all have an ID field; for new instances it gets assigned with a globally unique (incrementing) ID number
  • References between types that might introduce circles use an ID instead of containing the data, so in your example you would have an Id<Person> parent field

You might reasonably ask, why go to all the trouble of having immutable types only to introduce something like pointers back into the equation--since what the ID points to can change over time. The answer is, you can control updates to that global map in one place, e.g. accumulating then committing changes to it, rolling back if needed, etc. So you still have plenty of control.

@AlexanderJohr
Copy link
Author

Thanks again! I will try that. It sounds promising, because like that I can create a ViewModel fairly easy by wrapping a data class inside a BehaviorSubject or a regular Stream. The view would only need to have a StreamBuilder, listening to that Stream. Nested ViewModels would have their own simple data class also wrapped inside BehaviorSubject or Stream. Instead of updating the whole tree, because one leaf node changes, I can just modify that one leaf node.

This resolves a lot of difficulties.

All but one:
I would need to garbage collect dead nodes myself, am I correct? A deeply nested built_value Model has at least the advantage, that deleting a node, deletes all child nodes with it.
Deleting a node which holds an ID to another node, does not delete the nested node automatically by looking up the ID in the map. I would need to put such an approach inside a destructor. But Dart does not have destructors. What would you advice?

@davidmorgan
Copy link
Collaborator

Yes, you will need something to find and remove dead nodes.

If all your nodes implement an interface that returns all the Ids they reference, then you could do that as a global step where you compute all "reachable" nodes then discard the rest. Just like a garbage collector :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants