to_string_extension 0.5.0 to_string_extension: ^0.5.0 copied to clipboard
Uses class_extensions to generate toString for nicely looking text representation of data objects.
Description #
Uses class_extensions to generate toString for nicely looking text representation of data objects.
See also withers_extension, json_extension
Tutorial #
-
We need a class to generate toString for.
${PROJECT_ROOT}/lib/model.dart
import 'package:meta/meta.dart'; @immutable class SomeValueClass { final String strVal; final int intVal; SomeValueClass(this.strVal, this.intVal); }
-
For toString to work you need to add some boiler plate:
part 'model.g.dart';
- annotation
@ToString()
- mixin
_$SomeValueClass
${PROJECT_ROOT}/lib/model.dart
import 'package:meta/meta.dart'; import 'package:to_string_extension_annotations/annotations.dart'; part 'model.g.dart'; @ToString() @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.yaml
targets: $default: builders: class_extensions: generate_for: - lib/*.dart
-
Add dependencies.
${PROJECT_ROOT}/pubspec.yaml
name: example dependencies: to_string_extension_annotations: ^0.1.0 dev_dependencies: build_runner: ^1.0.0 to_string_extension: ^0.2.0
-
Run code generation:
pub run build_runner build
. File${PROJECT_ROOT}/lib/model.g.dart
should be created. -
If everything goes well you should be able to print a nice looking text representation of your object.
${PROJECT_ROOT}/bin/main.dart
import 'package:example/model.dart'; void main() { print(SomeValueClass("some", 0).toString()); // prints SomeValueClass(strVal=some, intVal=0) }
-
You can also see the example.