I am generating a set for selected items on tap of the iconbutton. But only one item is added in set and others are removed.
This is a code for selecting favorite items from the image grid created from a image list. When tapping on the Icon itemname should be added to the set. Right now when i tap on the icon it adds the item in the set and tapping other item it is removing previous item and adds new item. So at all times set is either empty or having only one item.
class TravelDestinationItem extends StatefulWidget {
TravelDestinationItem({Key key, @required this.destination, this.shape})
: assert(destination != null),
super(key: key);
static const double height = 566.0;
final Item destination;
final ShapeBorder shape;
final Set<String> saved = Set<String>();
@override
_TravelDestinationItemState createState() => _TravelDestinationItemState();
}
class _TravelDestinationItemState extends State<TravelDestinationItem> {
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final TextStyle titleStyle =
theme.textTheme.headline.copyWith(color: Colors.white);
final TextStyle descriptionStyle = theme.textTheme.subhead;
final String itemname=widget.destination.itemname;
final bool alreadySaved = widget.saved.contains(itemname);
return SafeArea(
top: false,
bottom: false,
child: GestureDetector(
child: Container(
padding: const EdgeInsets.all(4.0),
height: TravelDestinationItem.height,
child: Card(
shape: widget.shape,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
height: 150.0,
child: Stack(
children: <Widget>[
Positioned.fill(
child: Image.asset(
widget.destination.imagename,
fit: BoxFit.scaleDown,
),
),
Container(
alignment: Alignment.topLeft,
child: IconButton(icon:Icon(
alreadySaved
? Icons.favorite
: Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
),
onPressed : (){setState((){
if (alreadySaved) {
widget.saved.remove(itemname);
} else {
widget.saved.add(itemname);
print(widget.saved);
}
});}
),
),
],
),
),
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0.0),
child: DefaultTextStyle(
style: descriptionStyle,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
widget.destination.itemname,
style: descriptionStyle.copyWith(
color: Colors.black87),
),
),
],
),
),
),
),
],
),
),
)));
}
}