我有一个简单的卡片设计,我的卡片用一个特定高度和宽度的容器包裹,所以孩子们是有界的
卡片底部有一张来自Image.network
的图片和一段文字,两者都占据了卡片的一半高度
然而,我的代码收到了这个错误:
Error: Cannot hit test a render box that has never been laid out.
据我所知,约束从树上下来,子代将大小返回给父代。我知道这个列不会将约束传递给孩子,但是,两个扩展的小部件应该知道会占据卡片高度的一半吗?
我的目标是理解为什么这不起作用,此外还有实际的工作代码。非常感谢。
代码:
var height = MediaQuery.of(context).size.height;
return Container(
height: height * 0.45,
width: double.infinity,
child: Card(
elevation: 4,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
child: Column(
children: [
Expanded(
flex: 1,
child: FittedBox(
child: Image.network('https://source.unsplash.com/random'),
),
),
Expanded(
flex: 1,
child: Container(
child: Text("hello"),
),
)
],
)),
);
问题是FittedBox
试图相应地缩放其子级;因此,孩子需要先躺好。因为在本例中,子对象是要加载的图像,所以它不会放置在管件之前。为了克服这个问题,您可以使用SizedBox.expand
而不是FittedBox
:
Container(
height: height * 0.45,
width: double.infinity,
child: Card(
elevation: 4,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
child: Column(
children: [
Expanded(
flex: 1,
child: SizedBox.expand(
child: Image.network('https://source.unsplash.com/random'),
),
),
Expanded(
flex: 1,
child: Container(
child: Text("hello"),
),
)
],
)),
)
-在返回之前,不要在构建Methode内部使用MediaQuery。
-避免多余的争论:https://dart-lang.github.io/linter/lints/avoid_redundant_argument_values.html对于柔性:1
- 使用fit:BoxFit.contain
return Container(
height: MediaQuery.of(context).size.height* 0.45,
width: double.infinity,
child: Card(
elevation: 4,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
child: Column(
children: [
Expanded(
flex: 1,
child: Image.network('https://source.unsplash.com/random',fit: BoxFit.contain),
),
Expanded(
flex: 1,
child: Container(
child: Text("hello"),
),
)
],
)),
);