Home > Software engineering >  Flutter GridView off screen widgets destroyed on scroll
Flutter GridView off screen widgets destroyed on scroll

Time:06-21

I have a screen with a GridView widget containing custom Cards with images and texts. When the app initially launches it loads all the cards and their images, however, they get destroyed when scrolled off the screen. Is there a way that I can stop flutter from destroying the off-screen widgets?

Expanded(
 child: GridView.builder(
 gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  crossAxisCount: 2,
  childAspectRatio: 1.5,
 ),
  itemCount: categories.length,
  itemBuilder: (context, index) => CategoryCard(
   category: categories[index],
  ),
 ),
),

CodePudding user response:

Give flex or shrinkWrap: true, or use both

Expanded(
   flex: 3, <--
child: GridView.builder(
     shrinkWrap: true,  <--
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
  childAspectRatio: 1.5,
    ),
 itemCount: categories.length,
  itemBuilder: (context, index) => CategoryCard(
 category: categories[index],
   ),
  ),
 ),

CodePudding user response:

Figured it out! GridView, ListView, etc., have addAutomaticKeepAlives and cacheExtent properties. By default addAutomaticKeepAlives: true doesn't destroy off-screen widgets, and providing the cacheExtent: DOUBLE VALUE describes how many pixels the cache area extends before the leading edge and after the trailing edge of the viewport.

  • Related