应该在类中还是在build()函数中创建Flutter小部件? [英] Should Flutter widgets be created in the class or in the build() function?

查看:124
本文介绍了应该在类中还是在build()函数中创建Flutter小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

where 上是否有一般的经验法则来创建更优化的小部件(假设该小部件不依赖传递给build()的任何东西)?

Is there a general rule of thumb on where to create widgets to be more optimal (assuming the widget doesn't rely on anything passed into build())?

如果我们在类内创建小部件:

If we create a Widget inside the class:

Foo({Key key}) : super(key: key);
Widget _widget = new Container(); // Create here?

我们仅在创建类时创建一次。但是,如果未始终在build()中使用此小部件,则它可能会占用空间(例如,后台小部件,或者该小部件的可见性由标记确定)。

we only create it once when the class is created. However, this widget may sit around taking up space if it isn't always being used in build() (e.g. an offstage widget, or the visibility of the widget is determined by a flag).

如果我们在build()中创建窗口小部件:

If we create the widget inside build():

@override
Widget build(BuildContext context) {
Widget widget = new Container(); // Or create here?
  return widget;
}

每次调用build()都会重新创建该小部件,这感觉很昂贵

The widget gets re-created on every build() call, which feels costly, especially if the widget isn't changing.

推荐答案

在Flutter / Dart中构造短期对象通常非常便宜,并且小部件层负责确保除非进行小部件更改,否则重建时不会修改渲染树。因此,在正常情况下,缓存小部件并没有太大帮助。我倾向于在您的 build()方法中构造窗口小部件,除非出于某种原因该方法不起作用。

Constructing short-lived objects is generally very cheap in Flutter/Dart, and the widgets layer takes care of making sure that the render tree isn't modified on rebuilds unless the widget changes. So caching widgets doesn't help much in normal situations. I'd lean towards constructing widgets in your build() method unless there's a reason why that won't work.

这篇关于应该在类中还是在build()函数中创建Flutter小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆