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 Part from the Whole
  • set: Update the Whole with a new Part value, returning a new Whole

Key properties (lens laws):

  1. Get-Put: Setting the same value back returns the original: set(w, get(w)) == w
  2. Put-Get: Getting after setting returns the set value: get(set(w, p)) == p
  3. 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 get and set functions.
const

Properties

get → Part Function(Whole)
Extracts the focused Part from the Whole.
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 Whole with a new Part value, returning a new Whole.
final

Methods

modify(Whole whole, Part f(Part)) → Whole
Applies a transformation to the focused Part and updates the Whole.
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