Flutter GridView.count未显示所有项目



我试图使用GridView.count显示数据,但它并没有显示所有项目。这是我的代码


class CategoriesBody extends StatefulWidget {
const CategoriesBody({Key? key}) : super(key: key);
@override
_CategoriesBodyState createState() => _CategoriesBodyState();
}
class _CategoriesBodyState extends State<CategoriesBody> {

Widget header() {
return Center(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
width: MediaQuery.of(context).size.width,
child: Container(
color: appThemeColor,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Align(
alignment: Alignment.topLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
customText(context, "Available", 25.0,
FontWeight.w600, Colors.white),
customText(context, "Categories", 35.0,
FontWeight.w600, Colors.white),
]))))),
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
child: objResult == ""
? Column(
children: [
header(),
showCircularLoader(context),
],
)
: objResult == "not connected"
? Column(
children: [
header(),
SizedBox30(),
noInternetConnection(context)
],
)
: apiError == "Server down"
? Column(
children: [
header(),
SizedBox30(),
serverError(context),
],
)
: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
header(),

//list of all categries
SizedBox(
height: MediaQuery.of(context).size.height *
0.97,
child: GridView.count(
crossAxisCount: 2,
scrollDirection: Axis.vertical,
children: List.generate(category.length,
(index) {
return InkWell(
child: customCategoryContainer(
context,
"assets/img/cat2.jpg",
category.length != 0
? category[index].title
: "",
18.0,
MediaQuery.of(context)
.size
.height *
0.18,
MediaQuery.of(context)
.size
.height *
0.18));
}))),

]))));
}
}

api响应计数为12,但它显示10个项目。请在我做错的地方帮忙。

项目可能在那里,但大于屏幕高度。因为你有一个SingleChildScrollView,它是一个可滚动的小部件,那么网格是不可滚动的,网格和标题总共占据了屏幕的整个高度,并且不超过这个高度,所以SingleChildScrollView也是不可滚动。

我能想到的一个解决方案是禁用SingleChildScrollView小部件的滚动,并强制网格始终滚动,如下所示:

SingleChildScrollView(
physics: const NeverScrollableScrollPhysisc(),
//...
child: Column(
children: [
//...
SizedBox(
height: MediaQuery.of(context).size.height                                        * 0.97,
child: GridView.count(
physics: const AlwaysScrollableScrollPhysics(),
//...
)
),
]
),
)

这将使标题固定,并且网格可以在它所占据的屏幕高度内滚动。

SingleChildScrollView(
physics: const NeverScrollableScrollPhysisc(),
//...
child: Column(
children: [
//...
Expanded(
child: GridView.count(
physics: const AlwaysScrollableScrollPhysics(),
//...
)
),
]
),
)

如果有人出现此错误,则将GridView.countSizedBox的高度设置为全屏高度,这样就解决了问题。

最新更新