I am new to Flutter and have been trying to create a horizontal list with images where I can display some data. I attempted to use ListView.builder
, but unfortunately, it doesn't seem to work as expected. I also searched for solutions on Stack Overflow, but none of them resolved my issue.
What I want to achieve is a horizontal list with images like this: Flutter Horizontal List Image. Additionally, I want to change the color of the selected item to indicate that it's currently selected. However, I need to ensure that only one item can be selected at a time. So, when I select another item, the previously selected item should be deselected.
I would appreciate any help or guidance on how to implement this behavior effectively. Thank you in advance for your assistance!
You need to provide height while using horizontal listView. A great video about Unbounded height / width | Decoding Flutter
You can play with this widget.
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int? _selectedIndex; // if you want to provide default selection, init here
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
SizedBox(
height: 30,
), //top level space
SizedBox(
height: 68, // play with height
child: ListView.builder(
itemCount: 33, //number of item you like show
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () {
setState(() {
_selectedIndex = index;
});
},
child: Container(
alignment: Alignment.center,
width: 48,
height: 48,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color:
_selectedIndex == index ? Colors.blue : Colors.grey,
),
child: Text("$index"),
),
),
);
},
),
)
],
),
);
}
}
Check more about layout on flutter.dev