Reputation: 3899
I have simple horizontal ListviewBuilder, inside it i have card which can be selected . But the problem is , when i selected one of card , all card is selected. I want is i only can selected 1 card, if i pick another card , deleted old selected and create new selected to the new card. How to do this ?
Something like this :
My Failed Result
import 'package:flutter/material.dart';
class IconMenu {
final IconData iconName;
final String titleIcon;
IconMenu({this.iconName, this.titleIcon});
}
List<IconMenu> iconList = [
IconMenu(iconName: Icons.ac_unit, titleIcon: "AC Unit"),
IconMenu(iconName: Icons.access_alarm, titleIcon: "Alarm"),
IconMenu(iconName: Icons.accessibility_new, titleIcon: "accessiblity"),
IconMenu(iconName: Icons.add, titleIcon: "Add"),
];
class TestingScreen extends StatefulWidget {
static const routeName = "/testing-page";
@override
_TestingScreenState createState() => _TestingScreenState();
}
class _TestingScreenState extends State<TestingScreen> {
bool selectedList = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: iconList.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: () => setState(() => selectedList = !selectedList),
child: Container(
width: 150,
child: Card(
shape: selectedList
? RoundedRectangleBorder(
side: BorderSide(color: Colors.green))
: null,
elevation: 5,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(iconList[index].iconName),
Text(iconList[index].titleIcon)
],
),
),
),
);
},
),
)
],
),
);
}
}
Upvotes: 1
Views: 9173
Reputation: 1969
You should take a int
for the selected index.
int selectedIndex=-1
Then You can check for every card if its position
is equal to the selectedIndex
then its selected.
class _TestingScreenState extends State<TestingScreen> {
int selectedIndex = -1;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 200,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: iconList.length,
itemBuilder: (BuildContext context, int position) {
return InkWell(
onTap: () => setState(() => selectedIndex=position),
child: Container(
width: 150,
child: Card(
shape: (selectedIndex==position)
? RoundedRectangleBorder(
side: BorderSide(color: Colors.green))
: null,
elevation: 5,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(iconList[position].iconName),
Text(iconList[position].titleIcon)
],
),
),
),
);
},
),
)
],
),
);
}
}
Upvotes: 9