Skip to content

Improve debuggability of Widgets returned from extension factory methods #112468

@blaugold

Description

@blaugold

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):

  1. 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.
  2. Code in the described style does not mirror the element tree in the same way the more traditional style does.
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    r: invalidIssue is closed as not valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions