Opt In flag to generate builder class
Closed this issue · 1 comments
Use case:
A form with MyFormData
as a mappable class. The form data is constructed one step at a time from user input. I want MyForMyDataBuilder
that has the same fields as MyFormData
, but they're all nullable and I can set. I can then convert a builder into the final object with an informative exception thrown if not all required fields were set.
Here is one such way this could be implemented, though there are a ton of different approaches between which I have no strong preferences:
MyFormDataBuilder builder = MyFormDataBuilder(); // <- zero arg constructor, everything initialized to null
final String foo = await promptUserForFoo();
// Could just a regular setter like `builder.foo = foo;`, exact syntax isn't important.
builder.setFoo(foo);
final int bar = await promptUserForBar();
builder.setBar(bar);
final MyFormData formData = builder.create(); // <- throws if any required field is null
// ^ could have a [bool strict = false] optional arg that, if true, throws if a null field was
// never set so that nullable fields would have to be explicitly set to null.
MyDatabase.instance.table('forms').insert(formData.toMap());
Although I understand the use-case this is not something I would add to the package, as its not part of the core purpose of it and would further increase the api surface of it, which I try to keep as small as possible.
I think this can be added outside of dart_mappable with some additional code-generation. If you don't like writing a custom Builder, I can recommend another package of mine you could use to easily generate the Builder class yourself: super_annotations.