Failed assertion: line 482 pos 12: 'crossAxisExtent > 0.0': is not true

Viewed 1368

I am new in development, in general, I want to make a Grid list with a custom list but I faced some issues that one of them.

Categories Screen:

import 'package:flutter/material.dart';
import 'package:meals_app/widgets/category_item.dart';
import 'package:meals_app/dummy_data.dart';

class CategoriesScreen extends StatelessWidget {
  const CategoriesScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DeliMeal'),
      ),
      body: GridView(
        padding: const EdgeInsets.all(25),
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 200,
          childAspectRatio: 3 / 2,
          crossAxisSpacing: 20,
          mainAxisSpacing: 20,
        ),
        children: DUMMY_CATEGORIES
            .map(
              (catData) => CategoryItem(
                id: catData.id,
                title: catData.title,
                color: catData.color,
              ),
            )
            .toList(),
      ),
    );
  }
}
1 Answers

For a vertical list, the crossAxisExtent is the width of the sliver. So the assertion means that you did not give your widget a width, try wrapping your GridView in a Container and give it max width, like the following:

Container(
    width: MediaQuery.of(context).size.width,
    child: GridView(
      padding: const EdgeInsets.all(25),
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 200,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 20,
        mainAxisSpacing: 20,
      ),
      children: DUMMY_CATEGORIES
          .map(
            (catData) => CategoryItem(
              id: catData.id,
              title: catData.title,
              color: catData.color,
            ),
          )
          .toList(),
    ),
  ),

You can actually follow the source code of SliverGridDelegateWithMaxCrossAxisExtent and see where exactly the assertion is coming from, as you will see, the crossAxisExtent is from the SliverConstraints class, and you can see its documentation saying :

"The number of pixels in the cross-axis. For a vertical list, this is the width of the sliver."

Related