gpt4 book ai didi

flutter - Set 始终设置为空,即使在 flutter 中通过 set.add() 方法向其添加数据也是如此

转载 作者:IT王子 更新时间:2023-10-29 07:10:39 26 4
gpt4 key购买 nike

我在点击图标按钮时为所选项目生成一组。但是只有一个项目被添加到集合中,其他的被删除。

这是一个代码,用于从图像列表创建的图像网格中选择最喜欢的项目。点击图标时,应将项目名称添加到集合中。现在,当我点击图标时,它会在集合中添加项目并点击其他项目,它会删除以前的项目并添加新项目。所以在任何时候 set 要么是空的,要么只有一个项目。

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),

),
),

],
),
),
),
),

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

最佳答案

StatefulWidget 子类(不是 State)中包含的任何内容都必须是不可变的。

不能做类似widget.mySet.add(something)的事情。这将导致你的状态不受控制地丢失。

取而代之的是让 State 子类在内部存储一个 Set,并使用它

关于flutter - Set 始终设置为空,即使在 flutter 中通过 set.add() 方法向其添加数据也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57494511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com