functional_widget
A code generator to write widgets as function without loosing the benefits of classes.
Widgets are cool. But classes are quite verbose:
So much code for something that could be done much better using a plain function:
The problem is, using functions instead of classes is not recommended:
- https://stackoverflow.com/questions/53234825/what-is-the-difference-between-functions-and-classes-to-create-widgets/53234826#53234826
- https://github.com/flutter/flutter/issues/19269
... Or is it?
functional_widgets, is an attempt to solve this issue, using a code generator.
Simply write your widget as a function, decorate it with a @swidget
, and then
this library will generate a class for you to use.
As the added benefit, you also get for free the ability to inspect the parameters
passed to your widgets in the devtool
Example
You write:
It generates:
And then you use it:
How to use
Install (builder)
There are a few separate packages you need to install:
functional_widget_annotation
, a package containing decorators. You must
install it asdependencies
.functional_widget
, a code-generator that uses the decorators from the previous
packages to generate your widget.build_runner
, a dependency that all applications using code-generation should have
Your pubspec.yaml
should look like:
That's it!
You can then start the code-generator with:
Customize the output
It is possible to customize the output of the generator by using different decorators or configuring default values in build.yaml
file.
build.yaml
change the default behavior of a configuration.
FunctionalWidget
decorator will override the default behavior for one specific widget.
debugFillProperties override
Widgets can be override debugFillProperties
to display custom fields on the widget inspector. functional_widget
offer to generate these bits for your, by enabling debugFillProperties
option.
For this to work, it is required to add the following import:
Example:
(You write)
(It generates)
Generate different type of widgets
By default, the generated widget by @FunctionalWidget()
is a StatelessWidget
.
It is possible to generate a HookWidget
instead (from https://github.com/rrousselGit/flutter_hooks)
There are a few ways to do so:
-
Through
build.yaml
:then used as:
-
With parameters on the
@FunctionalWidget
decorator: -
With the shorthand
@hwidget
decorator:
In any cases, flutter_hooks
must be added as a separate dependency in the pubspec.yaml
All the potential function prototypes
functional_widget will inject widget specific parameters if you ask for them.
You can potentially write any of the following:
You can then add however many arguments you like after the previously defined arguments. They will then be added to the class constructor and as a widget field:
- positional
- named:
- A bit of everything: