Search code examples
user-interfaceflutterdartmaterial-designuser-experience

How to break Horizontal Scroll List vertically?


I have a list view with horizontal scroll. Inside it, there are choice chips that can be selected. However, all the chips appear on one long horizontal line. I want them to break into another line when reaching the screen limit.

Then, the whole list view can be scrolled, with multiple vertical chip lines.

What I have:

ListView(children: <Widget>[
   Container(
   child: ListView(scrollDirection: 
   Axis.horizontal,
   children: <Widget>[ChoiceChipDisplay()]

Chip Display:

ChoiceChipDisplay() {
    List<Widget> choices = List();
    widget.reportList.forEach((item) {
      choices.add(Container(
        padding: const EdgeInsets.all(2.0),
        child: ChoiceChip(
          label: Text(item),
          labelStyle: TextStyle(
              color: Colors.black, fontSize: 14.0, fontWeight: FontWeight.bold),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30.0),
          ),
          backgroundColor: Color(0xffededed),
          selectedColor: Color(0xffffc107),
          selected: selectedChoice == item,
          onSelected: (selected) {
            setState(() {
              selectedChoice = item;
              print(selectedChoice)

I've tried to Wrap them and set a horizontal direction limit but it didn't work.


Solution

  • I think you can use Wrap

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: HomePage(),
        );
      }
    }
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ListView(
            children: <Widget>[
              Wrap(
                spacing: 4.0,
                children: <Widget>[
                  for (var i = 0; i < 30; i++)
                    ChoiceChip(
                      label: Text("item $i"),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.0),
                      ),
                      backgroundColor: Color(0xffededed),
                      selectedColor: Color(0xffffc107),
                      selected: false,
                      onSelected: (b) {},
                    )
                ],
              ),
            ],
          ),
        );
      }
    }
    

    enter image description here