I have created list of cateogories using list listview.builder

here I want to highlight selected category by underlining category text with container and I want to apply width based on text length...same way like we do underline for text,

I know they are inbuilt some packages but I don't want to use it as I want to implement my logic.

here is my code

I have set comment where I want to dynamic width

class CatogoryList extends StatefulWidget {

  @override
  State<CatogoryList> createState() => _CatogoryListState();
}

class _CatogoryListState extends State<CatogoryList> {
  List<String> categories=['HandBag','Jwellery','FootWear','Dresses','Pens','Jeans','Trousers'];
  int selectedindex=2;
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 30,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
          itemCount: categories.length,
          itemBuilder: (context,index){
        return buildCategory(index);

      }),
    );
  }

  Widget buildCategory(int index)
  {
    return GestureDetector(
      onTap: (){
        setState(() {
          selectedindex=index;
        });
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
          Text(categories[index],style: TextStyle(fontSize: 20,color: selectedindex==index?Colors.blue:Colors.grey),),
          if(selectedindex==index)
            Container(
// here I want to set widget of container based on text length
            height: 3,width: 30,color: Colors.blue,),

        ],),
      ),
    );
  }
}


Solution 1: eamirho3ein

just do this:

    Widget buildCategory(int index)
    {
        return Wrap(
              children: [
                GestureDetector(
                  onTap: (){
                    setState(() {
                       selectedindex=index;
                    });
                  },
                  child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                           Text(categories[index],style: TextStyle(fontSize: 20,color: selectedindex==index?Colors.blue:Colors.grey),),
                           if(selectedindex==index)
                              Container(
                                 // here I want to set widget of container based on text length
                              height: 3,width: 30,color: Colors.blue,),

                        ],
                      ),
                   ),
                )
            ],
        );
    }

and remove SizedBox( height: 30,)


Solution 2: Kaushik Chandru

A text bas a decoration property in which you can add an underline

Text(
  "${categories[index]}",
   style: TextStyle(decoration: 
  TextDecoration.underline),
 )