Flutter custom Widgets: function vs inheritance

168

Creating a separate build() context permits the framework to optimize builds. Factoring it as a method in the current build() removes that possibility.

Share:
168
Cedric
Author by

Cedric

📸@dev_pogi

Updated on December 27, 2022

Comments

  • Cedric
    Cedric over 1 year

    My code works. This is more of a question about conventions/good practices, so if you don't want to waste your time, don't read.

    I know that when you want to make your own custom widgets in Flutter, you should normally extend StatelessWidget/StatefulWidget.
    But is there any downside to using a function instead, that returns a StatelessWidget?
    I will give an example of a custom Widget I created (in both ways):

    function:

    Widget flagImage(String imagePath) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(7),
        child: Image.asset(
          imagePath,
          width: 60,
          height: 40,
          fit: BoxFit.fill,
        ),
      );
    }
    

    inheritance:

    class FlagImage extends StatelessWidget {
      String imagePath;
      FlagImage(this.imagePath);
    
      @override
      Widget build(BuildContext context) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(7),
          child: Image.asset(
            imagePath,
            width: 60,
            height: 40,
            fit: BoxFit.fill,
          ),
        );
      }
    }
    

    I could insert them as a child to another Widget like flagImage(imagePath) and FlagImage(imagePath) respectively.

    Is there any reason I should NOT use a function that returns a small, simple StatelessWidget?
    For really small Widgets, I prefer using the function, that's a few less LOC, just my personal preference.

  • Cedric
    Cedric over 3 years
    thanks for the answer :) "optimize builds", is that only when setState is called or also for the initial build?
  • Randal Schwartz
    Randal Schwartz over 3 years
    All builds, such as when things need to be re-laid-out because parents have changed, or children have changed, etc.