【问题标题】:How can I build 2 lined ListView.builder in Flutter如何在 Flutter 中构建 2 行 ListView.builder
【发布时间】:2021-06-24 16:13:18
【问题描述】:

谁能解释我如何将小部件构建为具有 2 行项目的 ListView builder。我有一个这种类型的例子,你可以通过下图查看:

【问题讨论】:

标签: flutter dart


【解决方案1】:

一个选项是使用 Wrap 小部件,方向设置为水平。

@override
Widget build(BuildContext context) {
  final lorem = [
    'accusamus',
    'dignissimos',
    'ducimus',
    'blanditiis',
    'praesentium',
    'voluptatum'
  ];

  return Container(
    height: 100,
    width: 250,
    child: Wrap(
      direction: Axis.horizontal,
      children: List.generate(
        lorem.length,
        (index) => Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(lorem[index]),
        ),
      ),
    ),
  );
}

【讨论】:

    【解决方案2】:

    这个 sn-p 应该可以帮助你。 你可以在https://dartpad.dev/028daa76945938f0e5c14aea6a8bf84b?null_safety=true试试看

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return SizedBox(
          width: 500.0,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: ['English', 'Russian', 'Spanish']
                    .map((language) => LanguageButton(
                          language: language,
                        ))
                    .toList(),
              ),
              SizedBox(height: 20,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: ['Some really long language', 'French', 'German']
                    .map((language) => LanguageButton(
                          language: language,
                        ))
                    .toList(),
              ),
            ],
          ),
        );
      }
    }
    
    class LanguageButton extends StatelessWidget {
      final String language;
    
      const LanguageButton({Key? key, required this.language}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return OutlinedButton(
          style: OutlinedButton.styleFrom(
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(30),
              ),
            ),
          ),
          onPressed: () {
            // TODO
          },
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 8.0),
            child: Text(language),
          ),
        );
      }
    }
    

    我使用了Column 而不是ListView.builder。也许这足以满足您的需要。要点是将每一行作为Row 并将mainAxisAlignment 设置为spaceBetween

    【讨论】:

    • 这是个好主意,谢谢,但这不是我需要的
    • 您到底需要什么?你能在问题中多说一点吗?
    • 我不需要带有语言按钮的可滚动列表视图构建器,按钮大小应该根据语言名称的长度自适应宽度
    猜你喜欢
    • 2022-01-20
    • 2021-09-07
    • 2021-05-12
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2021-06-07
    相关资源
    最近更新 更多