如何防止在Flutter中基于自定义逻辑重新渲染小部件? [英] How to Prevent rerender of a widget based on custom logic in flutter?

查看:50
本文介绍了如何防止在Flutter中基于自定义逻辑重新渲染小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从反应的背景来看,它有许多生命周期方法,在这些方法中,我可以决定是否重新渲染组件.当我有很多组件时,我最近遇到了性能问题,因为它必须重新渲染所有这些组件.

Coming from a react background, it had many life cycle methods where I could decide whether to rerender the component or not. I recently ran into performance problems in flutter when I have many number of components, because it had to rerender all those.

我有什么办法可以阻止这种重新渲染,或者可以对其进行更多控制来决定何时重新渲染而无需遍历小部件树?

Is there anything that I can do to prevent such rerender or have more control over it to decide when to rerender without having it traverse through the widget tree?

推荐答案

通常,由于呈现太多的小部件而导致性能问题时,您正在使用ListView或GridView.您可以通过使用ListView.builder()或GridView.builder()方法来防止此性能问题.ListView.builder和GridView.builder将仅呈现屏幕上的窗口小部件,从而防止出现性能问题.

Usually when you have performance issues because you are rendering too many widgets, you are using ListView or GridView. You can prevent this performance issue by using ListView.builder() or GridView.builder() methods. ListView.builder and GridView.builder will only render the widgets that are on screen, thus preventing performance issues.

以下是一些示例:

使用GridView:

With GridView:

GridView.builder(
  gridDelegate:
      SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (BuildContext context, int index) => _grid(data[index]),
) 

使用ListView:

With ListView:

ListView.builder(
  itemBuilder: (BuildContext context, int index) => _listItem(data[index]),
)

这篇关于如何防止在Flutter中基于自定义逻辑重新渲染小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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