skip to Main Content

I am trying to do create a view of ExpansionTile with ListView.builder as children. It works well but just if my ListView.builder become larger, it will need to take some time to render it which slightly affect the user expereince. Is there anyway to help to improve the performance for this?

Below is my sample code:

ExpansionTile(
  title: Text(title),
  controlAffinity: ListTileControlAffinity.trailing,
  initiallyExpanded: true,
  maintainState: true,  
  children: [
     ListView.builder(
          itemCount: data.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) => widgetList[index],
        )
  ])

2

Answers


  1. Here’s an improved version of your code with optimizations for better performance:

    ExpansionTile(
      title: Text(title),
      controlAffinity: ListTileControlAffinity.trailing,
      initiallyExpanded: true,
      maintainState: true,
      children: [
        ListView.builder(
          itemCount: data.length,
          shrinkWrap: false, // Changed to false for better performance
          itemBuilder: (context, index) {
            // Implement lazy loading or load a smaller subset of data initially
            // Make sure widgetList[index] is a lightweight widget
            return widgetList[index];
          },
        ),
      ],
    )
    

    Key Changes:

    1. Set shrinkWrap to false to avoid calculating the full size of the list initially.
    2. Ensure that widgetList[index] consists of lightweight widgets.
    3. You can implement lazy loading by dynamically loading more data as the user scrolls, although this might require a more complex state management solution.

    Remember, these are general guidelines, and the actual performance improvements may vary depending on your specific use case and data.

    Login or Signup to reply.
  2. 1. shrinkWrap

    I would suggest to get rid of shirnkWrap (if possible), as it calculates the size of all elements in the list.

    2. ItemBuilder

    Also, I recommend to be aware of the operations inside the itemBuilder, because it can slow down rendering the items.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search