flutterperformancewidgetrebuild

Performance declaring widget in build method


I saw this post on stack overflow

Performance difference between widget function and class

Where

class Option2 extends StatelessWidget {
  const Option2();

  Widget createDummyWidget() {
    return const Dummy();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: createDummyWidget(),
    );
  }
}

Has an impact on performance because it can cause unneeded rebuilds. But I was wondering if I have

class Option2 extends StatelessWidget {
  const Option2();

  @override
  Widget build(BuildContext context) {
    final myNonConstantWidget = Dummy();

    return SizedBox(
      child: myNonConstantWidget,
    );
  }
}

Would that have the same negative impact on performance (having those unneeded rebuilds)? Or would it be just a performant as

class Option2 extends StatelessWidget {
  const Option2();

  @override
  Widget build(BuildContext context) {    
    return SizedBox(
      child: Dummy(),
    );
  }
}

Because I see this happen often in Flutters own widgets, so I assumed it has no negative performance impact.


Solution

  • All 3 samples are effectively the same performance-wise.

    The performance issue you mentioned in the question is about an StatefulWidget where the whole widget would be rebuild when the _counter variable gets modified.

    Extracting methods has no negative performance impact in itself, but it can make code harder to read and in the context of a StatefulWidget it can cause you to loose track of what really needs to be rebuild.

    In instances like this flutter (dart) advises to do what's best for code readability and not to worry about what the compiler will do with your code.