Home > Enterprise >  Why do I have to do a hot reload to change the icon?
Why do I have to do a hot reload to change the icon?

Time:08-25

I'm trying to save the state of an icon, it should change on click, but it only changes on hot reload, what's my mistake?

IconButton -

IconButton(onPressed: () {
  if (_favorite == Icons.favorite_border) {
    _favorite = Icons.favorite;
   print(1111);
  } else {
    _favorite = Icons.favorite_border;
    print(2222);
  }
}, icon: Icon(_favorite, color: configColors.orange, size: 10,)),

setState -

IconData _favorite = Icons.favorite_border;
  void initState() {
    _favorite = Icons.favorite_border;
    super.initState();

  }

CodePudding user response:

Inside onPressed call the setState to update the UI for StatefulWidget

IconButton(onPressed: () {
  if (_favorite == Icons.favorite_border) {
    _favorite = Icons.favorite;
   print(1111);
  } else {
    _favorite = Icons.favorite_border;
    print(2222);
  }
  setState((){}); //here
}, icon: Icon(_favorite, color: configColors.orange, size: 10,)),

CodePudding user response:

Put the state variable that you are changing inside the setState.

IconButton(onPressed: () {
    setState(() {
        if (_favorite == Icons.favorite_border) {
            _favorite = Icons.favorite;
            print(1111);
        } else {
            _favorite = Icons.favorite_border;
            print(2222);
        }
    }
}, icon: Icon(_favorite, color: configColors.orange, size: 
10,)),

Calling setState() is critical, because this tells the framework that the widget’s state has changed and that the widget should be redrawn.

https://docs.flutter.dev/development/ui/interactive

  • Related