Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Prevent rerender of a widget based on custom logic in flutter?

Tags:

flutter

dart

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?

like image 574
Natesh bhat Avatar asked Nov 06 '22 22:11

Natesh bhat


1 Answers

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.

Here are some examples:

With GridView:

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

With ListView:

ListView.builder(
  itemBuilder: (BuildContext context, int index) => _listItem(data[index]),
)
like image 142
dshukertjr Avatar answered Dec 13 '22 13:12

dshukertjr