Flutter中,Stack中的Positioned Widget引起异常

11

当我尝试使用 Positioned widget 封装 PandemicCard 时,出现以下异常。如果我只渲染卡片而不使用 Positioned widget,则可以正常工作。

I/flutter ( 7331): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 7331): The following assertion was thrown during performLayout():
I/flutter ( 7331): RenderStack object was given an infinite size during layout.
I/flutter ( 7331): This probably means that it is a render object that tries to be as big as possible, but it was put
I/flutter ( 7331): inside another render object that allows its children to pick their own size.
I/flutter ( 7331): The nearest ancestor providing an unbounded height constraint is:
I/flutter ( 7331):   RenderFlex#2b18c relayoutBoundary=up2 NEEDS-LAYOUT NEEDS-PAINT OVERFLOWING
I/flutter ( 7331):   creator: Column ← Center ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ← CustomMultiChildLayout ←

对于这段代码,有人能帮我找出我的错误吗?

class PandemicCard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 120.0,
      width: 76.0,
      decoration: BoxDecoration(
          color: Colors.blue,
          boxShadow: [
            BoxShadow(
                blurRadius: 5.0,
                color: Colors.grey)
          ]),
      child: Text('Hi'),
    );
  }
}

class PandemicCardStackState extends State<PandemicCardStack> {
  // final _cards = <PandemicCard>[ PandemicCard(), PandemicCard()];
  final _cards = <PandemicCard>[ PandemicCard()];

  @override
  Widget build( BuildContext context) {
    return Stack(
      // This Bombs!
      children: <Widget>[ Positioned( left: 0.0, top: 0.0, child: _cards[0])]
      // This works!
      // children: <Widget>[ _cards[0]]
    );
  }
}

class PandemicCardStack extends StatefulWidget {
  @override
  PandemicCardStackState createState() => PandemicCardStackState();
}

3
堆叠组件的子组件不能仅限于定位类型小部件。必须至少有一个非定位类型小部件。 - dshukertjr
3个回答

22
在栈里添加一个空的Container作为child
@override
Widget build( BuildContext context) {
return Stack(
  children: <Widget>[ 
    Container(),
    Positioned( left: 0.0, top: 0.0, child: _cards[0]),
   ]
  );
 }

3
因为“Stack”小部件在构建时必须至少有一个具有静态尺寸的项。 - Mazin Ibrahim
2
我还不得不将 overflow: Overflow.visible 添加到 Stack 中,以使该项可见。 - Zeynal
1
@MazinIbrahim 这不是真的。只需要阅读 RenderStack 文档即可。我将复制与您的声明相关的部分:[...] 如果没有非定位的子元素,则堆栈会尽可能变大 [...] - Guilherme Matuella

4

其他解决方案:

(a) 将堆栈包装在已知高度的容器中:

Container(
  height: 50,
  child: Stack(
    children: [
      Positioned(top: 10, left: 10, child: Text('My child'))
  ]),
),

(b) 建议添加一个空的Container()和Clip.none:

Stack(
  clipBehavior: Clip.none,
  children: [
    Container(),
    Positioned(top: 10, left: 10, child: Text('My child'))
  ]),

2

由于这仍然是一个问题。我也找到了另一种选择。

您还可以在IntrinsicHeight小部件中包装堆栈。

IntrinsicHeight(
    child: 
        Stack( 
            children: [Positioned(top: 10, left: 10, child:Text('My child')
        )]
    ),
),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接