簡體   English   中英

我想對 Flexible 小部件施加高度限制

[英]I want to put height constraints on a Flexible widget

我的屏幕有三個小部件:

  1. 第一個是小部件的 ListView,可以通過按鈕增加小部件的數量。 我希望 ListView 只占用所需的空間,這就是我將它包裝在 Flexible 中的原因,但我不希望它超過 266 的高度。(如果它占用的空間超過 266px,它就會變得可滾動)。
  2. 第二個是一個小部件,它將占用所有剩余空間,它被包裹在 Expended 中。
  3. 第三個只是一個具有定義高度的按鈕。

代碼是這樣的:

Scaffold(
  body : Column(
           children:[
               Flexible(child: Widget1()),
               Expanded(child: Widget2()),
               Button(),
          ])
)

我嘗試將 Flexible 包裹在一個 ConstrainedBox 中並給它一個 266 的最大高度,但是 Widget1 占據了所有 266 的高度。

總之,我想讓Widget1占用需要的空間,但是不能超過266,誰有解決辦法嗎?

在 listview 中添加屬性shrinkwrap : true,並使用 BoxConstraints,maxheight: 266 將 Widget1 與容器包裹起來。

class UpdateListViewExample extends StatefulWidget {
  const UpdateListViewExample({Key? key}) : super(key: key);

  @override
  State<UpdateListViewExample> createState() => _UpdateListViewExampleState();
}

class _UpdateListViewExampleState extends State<UpdateListViewExample> {
  List list = [];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          body: Column(children: [
        Flexible(
          child: Container(
            constraints: const BoxConstraints(
              maxHeight: 266,
            ),
            color: Colors.grey,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Widget1(list: list),
            ),
          ),
        ),
        const Expanded(child: Widget2()),
        ElevatedButton(
          onPressed: () {
            list.add(list.length + 1);
            setState(() {});
          },
          child: const Text("Click Me"),
        ),
      ])),
    );
  }
}

class Widget1 extends StatelessWidget {
  const Widget1({Key? key, required this.list}) : super(key: key);

  final List list;

  @override
  Widget build(BuildContext context) {
    return ListView(
      shrinkWrap: true,
      children: [
        for (var item in list)
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              height: 40,
              color: Colors.blue,
              alignment: Alignment.center,
              child: Text(
                '$item',
                style: const TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          )
      ],
    );
  }
}

class Widget2 extends StatelessWidget {
  const Widget2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM