Flutter: How to use Wrap instead of ListView.builder?

0

Issue

In FutureBuilder, I need to create Wrap with elements but I don’t know how.

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);
        },
      );
    }
  },
)

I need to replace ListView.builder with something like Wrap.builder or something else.

Solution

Let’s say this is your List:

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

You can use it in Wrap:

  1. Using List.map

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

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

To answer your question:

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

Answered By – CopsOnRoad

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More