Use case
Many widgets have a single child and enhance that child in some way. Extensions on Widget that define methods which wrap the receiver in another widget enable a style of Flutter code that requires much less nesting and is more readable to some.
Take this example of a widget tree written in the traditional Flutter style:
Center(
child: Padding(
padding: EdgeInsets.all(8),
child: Text('Hello World'),
),
);
With the help of an extension on Widget, it can be rewritten like so:
Text('Hello World')
.padding(EdgeInsets.all(8))
.center();
extension WidgetExtensions on Widget {
Widget center() => Center(child: this);
Widget padding(EdgeInsetsGeometry padding) =>
Padding(padding: padding, child: this);
}
There are some downsides for this style (that I'm aware of):
- The factory methods in extensions cannot return
const widgets, even if the receiver is const.
I don't think this is a big problem, since more often than not the receiver cannot be const in the first place.
It might be possible to introduce simplified const extension methods in Dart, that only allow calling a const constructor.
- Code in the described style does not mirror the element tree in the same way the more traditional style does.
- Recorded widget instance creation locations point to the bodies of extension methods, which is not useful to developers.
This issue is about the last point.
Proposal
I would like to have the ability to mark an extension method as a widget factory. Debug tools would use the call site of such methods when they need the location of a widget instance in the source code.
Use case
Many widgets have a single child and enhance that child in some way. Extensions on
Widgetthat define methods which wrap the receiver in another widget enable a style of Flutter code that requires much less nesting and is more readable to some.Take this example of a widget tree written in the traditional Flutter style:
With the help of an extension on
Widget, it can be rewritten like so:There are some downsides for this style (that I'm aware of):
constwidgets, even if the receiver isconst.I don't think this is a big problem, since more often than not the receiver cannot be
constin the first place.It might be possible to introduce simplified
constextension methods in Dart, that only allow calling aconstconstructor.This issue is about the last point.
Proposal
I would like to have the ability to mark an extension method as a widget factory. Debug tools would use the call site of such methods when they need the location of a widget instance in the source code.