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,),
],),
),
);
}
}
CodePudding user response:
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: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(categories[index],style: TextStyle(fontSize: 20,color: selectedindex==index?Colors.blue:Colors.grey),),
if(selectedindex==index)
Container(height: 3,color: Colors.blue,),
],),
),
),
)
],
);
}
and remove SizedBox( height: 30,)
CodePudding user response:
A text bas a decoration property in which you can add an underline
Text(
"${categories[index]}",
style: TextStyle(decoration:
TextDecoration.underline),
)
CodePudding user response:
1
One way is to wrap the Column in an IntrinsicWidth and leave out the width from the Container. Like
Widget buildCategory(int index)
{
return GestureDetector(
onTap: (){
setState(() {
selectedindex=index;
});
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(categories[index],style: TextStyle(fontSize: 20,color: selectedindex==index?Colors.blue:Colors.grey),),
if(selectedindex==index)
Container(height: 3,color: Colors.blue,),
],),
),
),
);
}