maybe_copy_with 1.0.0
maybe_copy_with: ^1.0.0 copied to clipboard
A lightweight package that lets you write ergonomic `copyWith` methods WITHOUT any code generation or `build_runner`.
import 'package:maybe_copy_with/maybe_copy_with.dart';
void main() {
// Original instance
final john = User(name: 'John', age: 18, gender: 'Male');
// 1️⃣ Change a non‑nullable field — `gender` stays untouched
final bob = john.copyWith(name: 'Bob');
// or
// final bob = john.copyWith(name: 'Bob', gender: null);
// 2️⃣ Change both a non‑nullable and a nullable field
final alice = bob.copyWith(
name: 'Alice',
gender: 'Female'.maybe(), // wrap with .maybe() to *replace* nullable field
);
// 3️⃣ Explicitly reset the nullable field to null
final android = alice.copyWith(
gender: null.maybe(), // set to null via .maybe()
);
print(john); // User(name: John, age: 18, gender: Male)
print(bob); // User(name: Bob, age: 18, gender: Male)
print(alice); // User(name: Alice, age: 18, gender: Female)
print(android); // User(name: Alice, age: 18, gender: null)
}
class User with MaybeCopyWith<User> {
final String name;
final int age;
final String? gender;
const User({required this.name, required this.age, this.gender});
/// Returns a **new** [User] where only the fields you specify are changed.
///
/// * `name`, `age` – plain nullable params. Pass a new value to replace the
/// current one, or omit (leave `null`) to keep the existing value.
/// * `gender` – wrapped in [Maybe] so you have **three** options:
/// * `null` or omit → keep current `gender` value;
/// * `'Female'.maybe()` → set a new non‑null value;
/// * `null.maybe()` → explicitly reset to `null`.
@override
User copyWith({String? name, int? age, Maybe<String>? gender}) => User(
name: name ?? this.name,
age: age ?? this.age,
gender: gender.or(this.gender),
);
@override
String toString() => 'User(name: $name, age: $age, gender: $gender)';
}