Flutter:如何在Listview中使用Stack Widget

问题描述 投票:0回答:1

Listview中的Stack Widget,无法完全显示,这是我的代码

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('test stack'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          Container(height: 100, color: Colors.greenAccent),
          const SizedBox(height: 20),
          _getItem(),
        ],
      ),
    );
  }

  _getItem() {
    return Stack(
      children: [
        Positioned(
          top: 20,
          left: 0,
          right: 0,
          child: Container(
            height: 200,
            color: Colors.purple,
          ),
        ),
        Align(
          alignment: Alignment.topCenter,
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            color: Colors.amber,
            child: const Text('title'),
          ),
        )
      ],
    );
  }
}

这是结果

如您所见,紫色视图未完全显示

这样做的原因是堆栈的大小是由 noposition widget 决定的,因此堆栈的大小就是 amber widget 的大小。

但是,琥珀色小部件的内容不确定。我希望琥珀色的小部件能够完全显示。我该怎么办?

flutter dart flutter-listview
1个回答
1
投票

如果我正确理解你的问题,请将

_getItem()
替换为以下内容:

_getItem() {
  return Stack(
    children: [
      Container(
        height: 200,
        margin: const EdgeInsets.only(top: 20),
        color: Colors.purple,
      ),
      Align(
        alignment: Alignment.topCenter,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          color: Colors.amber,
          child: const Text('title'),
        ),
      )
    ],
  );
}

输出:

© www.soinside.com 2019 - 2024. All rights reserved.