Search code examples
flutterhorizontallistview

Create dynamic horizontal listview of items and select the first item by default in flutter


I want to create a horizontal list of elements in flutter. It will be like horizontal button type containers(not buttons) and I want the first item in the list to be selected when the page loads. Any suggestions would be appreciated.


Solution

  • Simply declare a variable which will hold list and the selectedIndex and then use this selected index to highlight the item selected:-

    int selectedIndex=0;//will highlight first item
    List<String> youList=['1,'2','3','4'];//suppose this is your dynamic list
    

    Now code for the horizontal listview:-

    SizedBox(
    height: 100,
    child: ListView.builder(
        shrinkWrap:  true,
        scrollDirection: Axis.horizontal,
        itemCount: yourList.length,
        itemBuilder: (context,index){
          return Container(
            width: 100,
            height: 100,
            color: selectedIndex==index?Colors.green:Colors.red,//now suppose selectedIndex and index from this builder is same then it will show the selected as green and others in red color
            child: ,//here you can show the child or data from the list
          );
        },
      )
    ),
    

    Above example shows highlighting the box if selected but you can modify as per your need like you want to show border for highlight or anything else..