Home > Net >  Build interactive flutter UI with class methods
Build interactive flutter UI with class methods

Time:11-22

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?

CodePudding user response:

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;
        }
      },
    );
  • Related