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

Generate lenses option #1053

Closed
laurenskz opened this issue Mar 22, 2024 · 1 comment
Closed

Generate lenses option #1053

laurenskz opened this issue Mar 22, 2024 · 1 comment
Assignees
Labels
enhancement New feature or request needs triage

Comments

@laurenskz
Copy link

Lenses are a concept from functional programming that essentially focus a field of an object. A clear example is:

final teacher = Person(name: "Arthur", age: 53);

print(Person$.name.of(teacher).value);
// -> "Arthur"

print(Person$.age.of(teacher).update(60);
// -> Person(name: "Arthur", age: 60)

print(Person$.name.of(teacher).map((name) => name.toUpperCase()));
// -> Person(name: "ARTHUR", age: 53)

What is a lens. Essentially the lens interface is very very simple:

mixin Lens<T,K>{
   //Gets field from parent
   K get(T t);
   //Updates parent to set field to the value
   T update(T t,K k);

   Lens<T,C> then<C>(Lens<K,C> lens);
}

The beauty of lenses is that you can compose them. And the best thing is that you can use them with widgets in flutter. Suppose you have a state somewhere in your application, and in that state you have a list of some objects. You also have a widget that can update objects of that type. But your widget actually doesn't care where it sends the changes to. Lenses allow this abstraction. They just allow you to edit a value of the type you're interested in somewhere. Imagine a complicated nested object. Then you can for example say: Department$.manager.then(Manager$.employees).then(List$.index(0)).then(Employee$.salary). If you then combine the lens with a getter and setter for the source object (for example a Cubit) you can give widgets a place to put their modifications. This eliminates the need to say in all your Cubits : setFieldX(X x) => emit(state.copyWith(x : x).

Generating lenses is very simple, the only thing required would be generating a class as follows:

class ClassNameLenses{
  static Lens<ClassName<T>, fieldType> fieldName<T>() => Lens(
          (subject) => subject.fieldName,
          (subject, value) => subject.copyWith(fieldName: value));
}

I added type arguments for the case the class has them. The generation is simple and the feature would be very powerful

@rrousselGit
Copy link
Owner

I have no plan on generating lenses. I'd suggest using a separate code-generator for this instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request needs triage
Projects
None yet
Development

No branches or pull requests

2 participants