首页 > 解决方案 > 如何在堆栈中定位小部件,但不匹配父级的宽度/高度?

问题描述

我想在我的堆栈的顶部中心放置一个小部件,但它被拉伸到父级的宽度,如下面的屏幕截图:

在此处输入图像描述

这是我正在使用的代码:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      key: key,
      appBar: AppBar(
        title: Text("Just a test app"),
      ),
      body: Stack(
        children: <Widget>[
          Positioned(
            left: 0,
            right: 0,
            child: Card(
              child: Text("A variable sized text"),
            ),
          ),
        ],
      ),
    );
  }

我想要实现的是这个(但在堆栈内): 在此处输入图像描述

标签: dartflutter

解决方案


将您包装CardAlignor Center

 Stack(
    children: <Widget>[
      Positioned( 
        top: 50,
        left: 0,
        right: 0,
        child: Center(
          child: Card(
            child: Text("A variable sized text"),
          ),
        ),
      ),
      Align(
        alignment: Alignment.topCenter, //that also works
        child: Card(
          child: Text("Another variable sized text"),
        ),
      )
    ],
  ),   

推荐阅读