【问题标题】:Flutter: How to use Wrap instead of ListView.builder?Flutter:如何使用 Wrap 而不是 ListView.builder?
【发布时间】:2019-10-24 18:51:50
【问题描述】:

FutureBuilder 中,我需要使用元素创建Wrap,但我不知道如何。

FutureBuilder(
  future: _getCategories(),
  builder: (BuildContext context, AsyncSnapshot snapshot){
    if(snapshot.data == null){
      return Text("Wait...");
    }else{
      return ListView.builder(
        itemCount: snapshot.data.length,
        itemBuilder: (BuildContext context, int index){
          return  Text(snapshot.data[index].category);
        },
      );
    }
  },
)

我需要将ListView.builder 替换为Wrap.builder 之类的内容或其他内容。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    假设这是你的List

    List<int> _items = List.generate(10, (i) => i);
    

    你可以在Wrap使用它:

    1. 使用 List.map

      Wrap(
        direction: Axis.vertical,
        children: _items.map((i) => Text('Item $i')).toList(),
      )
      
    2. 使用 for-each

      Wrap(
        direction: Axis.vertical,
        children: [
          for (var i in _items)
            Text('Item $i'),
        ],
      )
      

    回答你的问题:

    Wrap(
      children: snapshot.data.map((item) => Text(item.category)).toList().cast<Widget>(),
    )
    

    【讨论】:

    • 它给出错误type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Widget&gt;'
    • 你能告诉我你的snapshot.data返回什么吗?
    • 它返回一个对象列表
    • 是的,我知道但是什么样的对象,它们实际上是Object 并且您的代码在ListView.builder 上运行良好(您发布的当前代码)?
    • 这就是我的对象的样子 class CategoryPODO{ String category; int id; CategoryPODO({ this.category, this.id }); } 是的,它适用于我发布的代码。
    【解决方案2】:

    这里有一个解决方案,

    List tags = ['one','two'];    
    Wrap(
              children: [
                for (var item in tags)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Chip(
                      
                      label: Text(item),
                    ),
                  )
              ],
            ),
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2019-11-03
      • 2021-01-13
      • 2021-04-16
      • 1970-01-01
      • 2019-09-28
      • 2021-03-28
      • 2020-09-18
      • 2019-10-26
      相关资源
      最近更新 更多