draft 0.0.11 copy "draft: ^0.0.11" to clipboard
draft: ^0.0.11 copied to clipboard

Immer, but for dart. Convert between immutable and mutable objects.

Draft is immer, but for dart.

Convert any object into a mutable draft, modify it, then convert it back to the immutable version. All while using a comfy API :)

import 'package:draft/draft.dart';

part 'example.draft.dart';

@draft
class Foo {
  final int value;
  const Foo(this.value);
}

// Foo is immutable, but we can edit it with Draft
Foo foo = Foo(value: 1).draft()..value += 1;
print(foo.value); // 2

See the examples directory for more info.

Set up #

First, install it

dart pub add dev:build_runner dev:draft_builder draft

Next, define your drafts

import 'package:draft/draft.dart';

part 'example.draft.dart';

@draft
class Foo {
  final int value;

  const Foo({
    required this.value,
  });
}

Then run the build runner

dart run build_runner build --delete-conflicting-outputs

Now you can use your drafts!

void main() {
  final foo1 = Foo(value: 1);

  // Use the produce method
  final foo2 = foo1.produce((draft) {
    draft.value += 1;
  });
  assert(foo2.value == 2);

  // Or create drafts inline
  final fooDraft = foo.draft();
  fooDraft.value = 10;
  final foo3 = fooDraft.save();
  assert(foo3.value == 10);
}

Use cases #

Draft supports a variety of use cases and does its best to use native language features to make it easier to use.

Cascade notation #

Draft conviently supports cascade notation. You can update multiple values inline.

final foo = Foo(1, 2).draft()
  ..value1 += 1
  ..value2 += 5;

Nested drafts #

You can nest draftable classes inside of other draftable classes.

@draft
class A {
  final B b;
  A(this.b);
}

@draft
class B {
  final int value;
  B(this.value);
}

final a = A(B(1)).produce((draft) {
  draft.b.value += 1;
});

Collections #

You can modify collections inline. Draft will create copies of the collection, without affecting the original.

@draft
class C {
  final List<int> values;
  C(this.values);
}

final c = C([1, 2, 3]).produce((draft) {
  draft.values[0] += 1;
});

Equality #

Draft does not provide any sort of equality checking out of the box. If you want equality checking, consider using equatable

Contributing #

If you like the package and want to contribute, feel free to open and issue or create a PR. I'm always open to suggestions and improvements.


keywords: flutter, dart, immutable, mutable, immer, draft

3
likes
160
points
270
downloads

Publisher

verified publisherjosiahsaunders.com

Weekly Downloads

Immer, but for dart. Convert between immutable and mutable objects.

Repository (GitHub)
Contributing

Documentation

API reference

License

MIT (license)

More

Packages that depend on draft