简体   繁体   English

应该在类中还是在build()函数中创建Flutter小部件?

[英]Should Flutter widgets be created in the class or in the build() function?

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())? 是否有最佳方法可以在哪里创建小部件的一般经验法则(假设小部件不依赖传递给build()的任何东西)?

If we create a Widget inside the class: 如果我们在类内创建一个Widget:

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

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() (eg an offstage widget, or the visibility of the widget is determined by a flag). 但是,如果未始终在build()中使用此窗口小部件,则它可能会占用空间(例如,后台窗口小部件,或者该窗口小部件的可见性由标志确定)。

If we create the widget inside build(): 如果我们在build()中创建小部件:

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

The widget gets re-created on every build() call, which feels costly, especially if the widget isn't changing. 在每次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. 在Flutter / Dart中,构造短期对象通常非常便宜,并且小部件层负责确保除非重新构建小部件,否则在重建时不会修改渲染树。 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()方法中构造小部件,除非有原因不能解决。

There's usually no need to care about this optimisation. 通常无需关心这种优化。 But use the const constructor whenever possible. 但是,请尽可能使用const构造函数。

But keep in mind that you should use your models as widgets directly. 但是请记住,您应该将模型直接用作小部件。 You shouldn't have a Widget that take an instance of your model class as input. 您不应该具有将模型类的实例作为输入的Widget。 It's instead your model class that should have a build method. 相反,应该是您的模型类具有构建方法。 Consequence, when storing data in your state, you won't have to recreate a new widget everytimes Build is called. 结果,当以您的状态存储数据时,您不必在每次调用Build时都重新创建新的小部件。

A good example is the list of ChatMessage in flutter's codelab. 一个很好的例子是flutter的代码实验室中的ChatMessage列表。 https://codelabs.developers.google.com/codelabs/flutter/index.html#5 https://codelabs.developers.google.com/codelabs/flutter/index.html#5

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

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