简体   繁体   English

Flutter 自定义小部件:function 与 inheritance

[英]Flutter custom Widgets: function vs inheritance

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.我知道当你想在Flutter中制作你自己的自定义widget时,你通常应该扩展StatelessWidget/StatefulWidget。
But is there any downside to using a function instead, that returns a StatelessWidget?但是,使用返回 StatelessWidget 的 function 有什么缺点吗?
I will give an example of a custom Widget I created (in both ways):我将给出一个我创建的自定义小部件的示例(两种方式):

function: function:

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

inheritance: 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.我可以将它们作为子项分别插入到另一个 Widget,例如flagImage(imagePath)FlagImage(imagePath)

Is there any reason I should NOT use a function that returns a small, simple StatelessWidget?有什么理由我不应该使用 function 来返回一个小而简单的 StatelessWidget 吗?
For really small Widgets, I prefer using the function, that's a few less LOC, just my personal preference.对于非常小的 Widgets,我更喜欢使用 function,这会少一些 LOC,这只是我个人的喜好。

Creating a separate build() context permits the framework to optimize builds.创建一个单独的 build() 上下文允许框架优化构建。 Factoring it as a method in the current build() removes that possibility.将其作为当前 build() 中的方法进行分解消除了这种可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM