Flutter - 在列表中每行显示多个项目

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

在我的 Flutter 应用程序中,我需要根据属性 singleLine 显示每行包含一个或两个项目卡的列表。如果为 true,则该项目必须显示在整行中,如果为 false,则我需要检查下一个项目。如果两者都将 singleLine 设置为 false,那么我必须将两者显示在同一行中,否则两者将使用全宽显示在单独的行中。例如,考虑以下列表:

final cards = [
  {"title": "Item 1", "singleLine": true},
  {"title": "Item 2", "singleLine": false},
  {"title": "Item 3", "singleLine": false},
  {"title": "Item 4", "singleLine": true},
  {"title": "Item 5", "singleLine": true},
  {"title": "Item 6", "singleLine": false},
  {"title": "Item 7", "singleLine": true},
  {"title": "Item 8", "singleLine": false},
  {"title": "Item 9", "singleLine": false},
];

在这种情况下,我想在屏幕上显示它:

Item 1
Item 2   Item 3
Item 4
Item 5
Item 6
Item 7
Item 8   Item 9

我该怎么做?

flutter
1个回答
0
投票

我认为没有特定的小部件可以做到这一点,但可以通过使用一些逻辑来实现。

看下面的ListView的构建器:

class MyHomePage extends StatelessWidget {
  static const List<Map<String, dynamic>> cards = [
    {"title": "Item 1", "singleLine": true},
    {"title": "Item 2", "singleLine": false},
    {"title": "Item 3", "singleLine": false},
    {"title": "Item 4", "singleLine": true},
    {"title": "Item 5", "singleLine": true},
    {"title": "Item 6", "singleLine": false},
    {"title": "Item 7", "singleLine": true},
    {"title": "Item 8", "singleLine": false},
    {"title": "Item 9", "singleLine": false},
  ];

  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Column(
          children: [
            Text('One or two in a line'),
            Expanded(
              child: ListView.builder(
                  itemCount: cards.length,
                  itemBuilder: (context, index) {
                    if (index < cards.length - 1) {
                      if (cards[index]['singleLine'])
                        return Text(cards[index]['title']);
                      else {
                        if (!cards[index + 1]['singleLine']) {
                          return Row(
                            children: [
                              Text(cards[index]['title']),
                              SizedBox(
                                width: 25,
                              ),
                              Text(cards[index + 1]['title']),
                            ],
                          );
                        } else {
                          return Text(cards[index + 1]['title']);
                        }
                      }
                    }
                  }),
            )
          ],
        ));
  }
}

结果如下:

希望对您有帮助。

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