Consider this Flutter code snippet that builds a grid of colored squares. What will you see on the screen?
GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemCount: 6, itemBuilder: (context, index) { return Container( color: index % 2 == 0 ? Colors.red : Colors.blue, margin: EdgeInsets.all(4), ); }, )
Look at the crossAxisCount and the color condition using index % 2 == 0.
The crossAxisCount: 3 means 3 columns. With 6 items, it forms 2 rows. The color alternates red for even indexes and blue for odd indexes, starting with red at index 0.
In Flutter's GridView.builder, when is the itemBuilder function called?
Think about how Flutter optimizes building large lists or grids.
GridView.builder builds items lazily. It calls itemBuilder only for items that are visible or about to be visible, improving performance.
You want each grid item to have a width twice its height. Which gridDelegate code achieves this?
Remember childAspectRatio is width divided by height.
Setting childAspectRatio: 2.0 means width is twice the height. Using SliverGridDelegateWithFixedCrossAxisCount with this ratio fixes the aspect ratio for all items.
Look at this code snippet:
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemCount: 5,
itemBuilder: (context, index) {
if (index == 4) return null;
return Container(color: Colors.green);
},
)Why does it cause an error?
What does itemBuilder expect to return?
itemBuilder must always return a non-null widget. Returning null causes a runtime error.
Choose the best explanation for why GridView.builder is more efficient than GridView.count for large data sets.
Think about how many widgets are created initially.
GridView.builder creates widgets only for items visible on screen, saving CPU and memory. GridView.count builds all widgets at once, which can be slow for many items.