Search code examples
flutterflutter-layout

Scrolling Wrap Widget With 2 lines and Variable Size Objects


I cannot figure out how to create a Scrolling Wrap Widget inside my app that displays a number of items over 2 lines and is scrollable Horizontally to reveal the lines content:

return
 SafeArea(
   child: SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: Wrap(
        direction: Axis.horizontal,
        runAlignment: WrapAlignment.center,
        children:[
          for (var i=0;i<10;i++)  Card(
            elevation: 6,
            color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(title,),
            ),
          ),
        ]
    ),
),
 );

The result for this is : enter image description here

I tired to wrap the Wrap with a Container with fixed height and every other combination imaginable and have not found a way to do this correctly, Basically I want to achieve a grid like functionality where the children are not all constrained to a fixed sized cell but are maintaining their variable width .

Expected result as requested would be a scroll-able list that looks like this:

enter image description here


Solution

  • This Answer Will Help You.

    List<String> list = ['Long text', 'Even longer text', 'Long text', 'Even longer text', 'Text', 'Text', 'Short text', 'Text', 'Short text', 'Long text', 'Even longer text'];
    
    SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 50,
                  child: ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    scrollDirection: Axis.horizontal,
                    itemCount: list.length,
                    itemBuilder: (context, index) {
                      return index.isEven ? CardWidget(list[index]) : Container();
                    },
                  ),
                ),
                SizedBox(
                  height: 50,
                  child: ListView.builder(
                    physics: NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    scrollDirection: Axis.horizontal,
                    itemCount: list.length,
                    itemBuilder: (context, index) {
                      return index.isOdd ? CardWidget(list[index]) : Container();
                    },
                  ),
                )
              ],
            ),
          )
    

    I refer from this solution.

    Output like this

    enter image description here