1

Is returning a widget in a switch case just as efficient as encapsulating that code in an other builder widget?

switchcase:

  @override
  Widget build(BuildContext context) {
    switch (predicate()) {
      case Trinary.first:
        return firstChildBuilder(context);
      case Trinary.second:
        return secondChildBuilder(context);
      case Trinary.third:
        return thirdChildBuilder(context);

Vs abstracting the switch out to a new widget with it's own build method,

@override
Widget build(BuildContext context) {
  return TrinaryBuilderWidget(
    predicate: viewModel.statusPredicate(),
    firstChildBuilder: (context) {
      return FirstWidget();
    },
    secondChildBuilder: (context) {
      return SecondWidget();
    },
    thirdChildBuilder: (context) {
      return ThirdWidget();
    },
  );
}


==========new class==========
class TrinaryBuilderWidget extends StatelessWidget {
  final Trinary Function() predicate;
  final WidgetBuilder firstChildBuilder;
  final WidgetBuilder secondChildBuilder;
  final WidgetBuilder thirdChildBuilder;

  /// Will build the widget associated with the [Trinary] specified by the [predicate]
  const TrinaryBuilderWidget({
    Key? key,
    required this.predicate,
    required this.firstChildBuilder,
    required this.secondChildBuilder,
    required this.thirdChildBuilder,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    switch (predicate()) {
      case Trinary.first:
        return firstChildBuilder(context);
      case Trinary.second:
        return secondChildBuilder(context);
      case Trinary.third:
        return thirdChildBuilder(context);
    }
  }
}
Dan Anderson
  • 1,062
  • 13
  • 26
  • Assuming you're talking about performance, it's not going to matter in any meaningful way in the vast majority of circumstances. – Robert Harvey Dec 07 '22 at 02:42
  • Yes actually these are rather large widget trees, and I need to keep the rendering as efficient as possible. – Dan Anderson Dec 07 '22 at 16:40

1 Answers1

0

Thinking logically for me, i think building another widget will take some resources of the app, so i think switch case gonna be more efficient than returning some other Widget()

Timur
  • 36
  • 2