withers_extension 0.9.0
withers_extension: ^0.9.0 copied to clipboard
Uses class_extensions to generate withers. Withers are a convenient way of constructing copies of immutable objects with altered values.
Description #
Uses class_extensions to generate withers. Withers are a convenient way of constructing copies of immutable objects with altered values.
See also to_string_extension, json_extension
Tutorial #
-
We need a class to generate withers for. You usually want to generate withers for immutable classes.
${PROJECT_ROOT}/lib/model.dartimport 'package:meta/meta.dart'; @immutable class SomeValueClass { final String strVal; final int intVal; } -
For withers to work you need to add some boiler plate:
part 'model.g.dart';- annotation
@Withers() - mixin
_$SomeValueClass - all args constructor
SomeValueClass(this.strVal, this.intVal);
${PROJECT_ROOT}/lib/model.dartimport 'package:meta/meta.dart'; import 'package:withers_extension_annotations/annotations.dart'; part 'model.g.dart'; @Withers() @immutable class SomeValueClass with _$SomeValueClass { final String strVal; final int intVal; SomeValueClass(this.strVal, this.intVal); } -
Configure code generation. More info at build.
${PROJECT_ROOT}/build.yamltargets: $default: builders: class_extensions: generate_for: - lib/*.dart -
Add dependencies.
${PROJECT_ROOT}/pubspec.yamlname: example dependencies: withers_extension_annotations: ^0.1.0 dev_dependencies: build_runner: ^1.0.0 withers_extension: 8.0.0 -
Run code generation:
pub run build_runner build. File${PROJECT_ROOT}/lib/model.g.dartshould be created. -
If everything goes well you should be able to use withers.
${PROJECT_ROOT}/bin/main.dartimport 'package:example/model.dart'; void main() { var some = SomeValueClass("some", 0); var other = some.withIntVal(1).withStrVal("other"); } -
You can also see the example.