Lens<Whole extends Object?, Part extends Object?> class
final
A functional lens for focusing on a part of a larger whole.
A Lens provides a composable way to get and update nested data structures without mutation. It consists of two functions:
- get: Extract the focused
Partfrom theWhole - set: Update the
Wholewith a newPartvalue, returning a newWhole
Key properties (lens laws):
- Get-Put: Setting the same value back returns the original:
set(w, get(w)) == w - Put-Get: Getting after setting returns the set value:
get(set(w, p)) == p - Put-Put: Setting twice is the same as setting once:
set(set(w, p1), p2) == set(w, p2)
These laws are assumed but not enforced by the type system.
Use cases:
- Accessing and updating deeply nested immutable structures
- Functional updates without mutation (especially useful with freezed/equatable)
- Composing transformations through multiple levels of data
- Decoupling business logic from data structure details
Example:
class Address {
const Address({required this.street, required this.city});
final String street;
final String city;
}
class Person {
const Person({required this.name, required this.address});
final String name;
final Address address;
}
// Create a lens focusing on a person's city
final cityLens = Lens(
get: (person) => person.address.city,
set: (person, newCity) => person.copyWith(
address: person.address.copyWith(city: newCity),
),
);
// Use it
final person = Person(name: 'Alice', address: Address(street: '123 Main', city: 'NYC'));
final updated = cityLens.set(person, 'LA'); // Person with LA, name unchanged
- Annotations
-
- @experimental
Constructors
- Lens({required Part get(Whole), required Whole set(Whole, Part)})
-
Creates a lens with the given
getandsetfunctions.const
Properties
- get → Part Function(Whole)
-
Extracts the focused
Partfrom theWhole.final - hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- set → Whole Function(Whole, Part)
-
Updates the
Wholewith a newPartvalue, returning a newWhole.final
Methods
-
modify(
Whole whole, Part f(Part)) → Whole -
Applies a transformation to the focused
Partand updates theWhole. -
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
then<
SubPart> (Lens< Part, SubPart> other) → Lens<Whole, SubPart> - Composes this lens with another lens to focus deeper.
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited