3
class ListItem extends StatefulWidget {
  final Product product;

  ListItem(this.bloc, this.product);

  @override
  _ListItemState createState() => _ListItemState(product);
}

class _ListItemState extends State<ListItem> {
  Product product;
  _ListItemState(this.product);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(product.title),
      trailing: LikeIcon(
        id: product.id,
        isFavourite: product.isFavorite,
        likeStatusHandler: toggleLikeStatus,
      ),
    );
  }
}

class LikeIcon extends StatefulWidget {
  final int id;
  final bool isFavourite;
  final Function(int) likeStatusHandler;

  LikeIcon({
    @required this.id,
    @required this.isFavourite,
    @required this.likeStatusHandler,
  });

  @override
  _LikeIconState createState() => _LikeIconState(isFavourite);
}

class _LikeIconState extends State<LikeIcon> {
  bool isFavourite;

  _LikeIconState(isFavourite) {
    this.isFavourite = isFavourite;
  }

  @override
  Widget build(BuildContext context) {
    return _favouriteWidget();
  }
}

Initially I had made the ListItem widget as a StatelessWidget with LikeIcon widget as StatefulWidget which controls the enabled/disabled state of the Like icon within itself. The problem I faced there was, when I scrolled the list, the state of the like was lost.

Later I made the ListItem itself as a StatefulWidget and it solved the problem. But seeing the logs I noticed that the ListItem is rebuilt (build method is being called) every time I scroll.

If the ListItem is a StatelessWidget then the build method is not getting called on scroll. Rebuilding the entire ListItem on every scroll is something that I'm concerned with especially with large datasets with images involved in it.

Any explanation on a deeper level is appreciated.

codingmonk21
  • 73
  • 2
  • 11

0 Answers0