Search code examples
jsonlistviewflutterscrollview

How to load multiple list view inside single list view?


I'm working on flutter app in which I want to show feeds, I want to show 1st list(Horizontal list) with 4 workouts, 2nd list (Vertical list) with 4 posts, 3rd list (Horizontal list) with 4 coaches and 4th list again 4 posts. At the end of list there is 'Load More' button and after click on button again repeating 1st step i.e. 4 workouts, 4 Posts, 4 Coaches and 4 Posts. My question is What is the best way to display this type of view.

Video For clear my points


Solution

  • Here is an example of what you want to achieve:

    List<List<String>> lists = [["A1","A2","A3","A4","A5"],["B1","B2","B3"],["C1","C2","C3","C4","C5"],["D1","D2","D3"]];
    
    Widget buildCard(String text) {
      return Container(
        margin: EdgeInsets.all(4.0),
        padding: EdgeInsets.all(40.0),
        alignment: Alignment.center,
        color: Colors.lightGreenAccent,
        child: Text(text),
      );
    }
    
    Widget buildHorizontalList(List<String> sublist) {
      return SizedBox(
        height: 200.0,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: sublist.length,
          itemBuilder: (context, index) => buildCard("${sublist[index]}"),
        ),
      );
    }
    
    Widget buildVerticalList(List<String> sublist) {
      return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: sublist.length,
        itemBuilder: (context, index) {
          return buildCard("${sublist[index]}");
        },
      );
    }
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        body: ListView.builder(
            itemCount: lists.length + 1,
            itemBuilder: (context, index) {
              if (index <= lists.length - 1) {
                return index.isEven ? buildHorizontalList(lists[index]) : buildVerticalList(lists[index]);
              }
              return RaisedButton(
                child: Text('Load More'),
                onPressed: () {
                  setState(() {
                    lists.addAll([["X1","X2","X3","X4","X5"],["Y1","Y2","Y3"]]);
                  });
                },
              );
            }),
      );
    }
    

    Edit: I added the Load More button functionality, basically the button just update the 'lists' variable (a list that contains all the sublists). Then the ListViews are being build according to the 'lists' content.