创建项目的动态水平列表视图并在flutter中默认选择第一项

问题描述

我想在Flutter中创建一个水平元素列表。它就像水平按钮类型的容器(不是按钮),我希望在页面加载时选择列表中的第一项。任何建议将不胜感激。

解决方法

只需声明一个将保存列表和 selectedIndex 的变量,然后使用此选定索引突出显示所选项目:-

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

现在为水平列表视图编写代码:-

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

上面的示例显示了选中时突出显示的框,但您可以根据需要进行修改,例如要显示突出显示的边框或其他任何内容..