Let's say I have a widget:
class MyWidget {
final Widget? leading;
final WidgetBuilder? trailing;
Widget build(BuildContext context) {
return Row(
children: [
if(leading != null ) leading,
AnotherWidget(),
if(trailing != null) trailing(context),
],
);
}
I am curious is there any pros/cons to use WidgetBuilder
instead Widget
for trailing
?
Yes, there are several essential differences between using a Widget
and WidgetBuilder
in Flutter:
Widget
, you pass an instance of a widget that is already built.WidgetBuilder
, you use a function that returns a widget, allowing deferred construction.Widgets
passed directly typically use the context they're given during construction.WidgetBuilders
can create and use a new context, which is useful for accessing inherited widgets or when the context might change.Widgets
passed directly generally don't need rebuilding with a new context.WidgetBuilders
allow rebuilding the widget with a new context, which can be necessary for certain scenarios.Widgets
are suitable when the widget's context is sufficient and doesn't need to change.WidgetBuilders
are suitable when the widget needs a new context or context-specific information that might change.Widgets
are simpler and more straightforward to use.WidgetBuilders
are slightly more complex due to the function and context handling involved.