按下后图标没有改变 - Flutter
Icon not changing after pressing it - Flutter
我正在创建收藏页面。对于每个产品页面,我在应用栏上放置了一个喜欢的图标,该图标可以更改并将特定产品添加到用户的收藏夹中。
按下图标后无法更改图标状态。
class FoodDetail extends StatefulWidget {
@override
_FoodDetail createState()=> _FoodDetail();
const FoodDetail({Key key}) : super(key: key);
}
class _FoodDetail extends State<FoodDetail>{
@override
Widget build(BuildContext context) {
FoodNotifier foodNotifier = Provider.of<FoodNotifier>(context);
_onFoodDeleted(Food food) {
Navigator.pop(context);
foodNotifier.deleteFood(food);
}
final _saved = Set<BuildContext>();
final alreadySaved = _saved.contains(context);
return Scaffold(
appBar: AppBar(
title: Text(foodNotifier.currentFood.name),
actions: <Widget>[
// action button
new IconButton(
icon: alreadySaved ? Icon(Icons.star) : Icon(Icons.star_border),
color: alreadySaved ? Colors.yellow[500] : null,
onPressed: (){
setState(() {
if (alreadySaved) {
_saved.remove(context);
} else {
_saved.add(context);
}
});}
您的状态不会改变,因为您将它们放在 build
方法中,该方法总是会重新初始化它们。
将您的状态 _saved
、alreadySaved
放在 build
方法之外。
final _saved = Set<BuildContext>();
final alreadySaved = _saved.contains(context);
@override
Widget build(BuildContext context) {
}
我正在创建收藏页面。对于每个产品页面,我在应用栏上放置了一个喜欢的图标,该图标可以更改并将特定产品添加到用户的收藏夹中。
按下图标后无法更改图标状态。
class FoodDetail extends StatefulWidget {
@override
_FoodDetail createState()=> _FoodDetail();
const FoodDetail({Key key}) : super(key: key);
}
class _FoodDetail extends State<FoodDetail>{
@override
Widget build(BuildContext context) {
FoodNotifier foodNotifier = Provider.of<FoodNotifier>(context);
_onFoodDeleted(Food food) {
Navigator.pop(context);
foodNotifier.deleteFood(food);
}
final _saved = Set<BuildContext>();
final alreadySaved = _saved.contains(context);
return Scaffold(
appBar: AppBar(
title: Text(foodNotifier.currentFood.name),
actions: <Widget>[
// action button
new IconButton(
icon: alreadySaved ? Icon(Icons.star) : Icon(Icons.star_border),
color: alreadySaved ? Colors.yellow[500] : null,
onPressed: (){
setState(() {
if (alreadySaved) {
_saved.remove(context);
} else {
_saved.add(context);
}
});}
您的状态不会改变,因为您将它们放在 build
方法中,该方法总是会重新初始化它们。
将您的状态 _saved
、alreadySaved
放在 build
方法之外。
final _saved = Set<BuildContext>();
final alreadySaved = _saved.contains(context);
@override
Widget build(BuildContext context) {
}