0

I have a ListView of projects where each ListTile represents a project. For that I have a List of projects which is written into the ListView with a for loop. Each ListTile has an IconButton to define a project as favourite. To keep the code clean I defined methods inside the project class to build the UI. The reason behind that is that the project can be set as a favourite from different locations in the application.

Unfortunately I cannot get the application to update the UI depending on the favorite status. I suppose it has something to do with the return of the Widgets, as the state gets evaluated once on return and does not change until refresh. I already extended the Project class with a ChangeNotifier without any result. Down below the code.

ListView(
  children: [
    for (var project in projects.projects) project.getListTile()
  ],
),

Project class with getListTile Method():

class Project extends ChangeNotifier{
bool favorite = false;
Project({this.favorite = false});

  IconButton getFavoriteButton() {
    return IconButton(
      icon: favorite
          ? Icon(Icons.favorite_outlined)
          : Icon(Icons.favorite_border_outlined),
      color: favorite ? Colors.yellow : Colors.white,
      onPressed: () {
        favorite = !favorite;
        notifyListeners();
      },
    );
  }
      
ListTile getListTile() {
    return ListTile(
      leading: getFavoriteButton(),
      ),
    );
}
}

Is there a way to refresh the UI, so that the favorite icon type and color updates on pressing the IconButton?

1 Answer 1

0

You should be using a StatefullWidget implementation.

These widgets are made to store a state and rebuild automatically on any state change when you do :

 IconButton(
      icon: favorite
          ? Icon(Icons.favorite_outlined)
          : Icon(Icons.favorite_border_outlined),
      color: favorite ? Colors.yellow : Colors.white,
      onPressed: () {
        setState((){
            favorite = !favorite;
        }
      },
    );
2
  • Is it possible to return a StatefullWidget with a method? Maybe I could extend the project class with a StatefullWidget? Would that make sense?
    – Raphael
    Commented Nov 21, 2021 at 19:57
  • I would transform your Project class directly in a Project Statefull widget. And use it directly in your widget tree
    – Jscti
    Commented Nov 21, 2021 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.