【发布时间】:2021-02-14 06:00:26
【问题描述】:
我有GridView,其crossAxisCount 为2。我希望GridView 的孩子的宽度与屏幕宽度的一半相同,同时保持正确的纵横比。
我的GridView的代码。
Container(
child: GridView.builder(
scrollDirection: Axis.vertical,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
shrinkWrap: true,
padding: EdgeInsets.all(8),
itemCount: albumsCovers.length,
itemBuilder: (BuildContext context, int index) {
return MyCard(
imageName: albumsCovers.elementAt(index),
text1: albumNames.elementAt(index),
text2: albumNames.elementAt(index),
);
},
),
),
我的自定义小部件的代码。我已经用Row 包裹了我的Image,因为没有Row 小部件Image 小部件不会扩展到GridView 子可用的最大宽度。
class MyCard extends StatelessWidget {
final String imageName;
final String text1,text2;
MyCard({this.imageName,this.text1,this.text2});
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
//without Row widget Image widget does not expand to the max available size to GridView child.
Row(
children: [
Expanded(
child: Image(image: AssetImage(this.imageName),),
),
],
),
SizedBox(height: 8),
Text(
this.text1,
overflow: TextOverflow.ellipsis,
softWrap: false,
maxLines: 1,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
Text(
this.text2,
overflow: TextOverflow.ellipsis,
softWrap: false,
maxLines: 1,
style: TextStyle(
fontSize: 14,
color: Color(0xFF8E8E8E),
),
),
],
),
);
}
}
我希望我的GridView 看起来像这样。但我在Image 下方的Text 被截断,Flutter 显示底部溢出。
注意:我已经有宽高比为 1:1 的图像。
这就是单个MyCard 的样子。
【问题讨论】:
-
尝试
childAspectRatio:itemWidth / itemHeight在SliverGridDelegateWithFixedCrossAxisCount中使用,在gridview@user11862325中使用自定义itemwidth和itemHeight -
@Assassin
itemWidth总是屏幕大小的一半,所以我可以轻松获得itemWidth。但是我如何才能得到itemHeight?Text会根据不同的手机尺寸和用户的喜好有不同的尺寸。 -
你试过
MediaQuerymedium.com/tagmalogic/…@user11862325 -
@Assassin 我读过你提到的那篇文章。但这仍然不能解决我的问题。我知道我可以通过计算
(0.5)*MediaQuery.of(context).size.width得到itemWidth。和itemHeight将是itemHeight = itemWidth + (height of the 2 Text widget + 8)这根本不依赖于屏幕高度。
标签: flutter gridview flutter-layout