Flutter Pagination & Provider: setState() or markNeedsBuild() called during build in NotificationListener

I am currently building a GridView for an image gallery in Flutter, utilizing a provider to manage my media list and to integrate a caching system. The GridView is designed to work with pagination, where the first 30 items are fetched and displayed, and additional items are fetched only when the user scrolls to the bottom of the ListView. The GridView is shrink-wrapped inside the ListView to accommodate additional widgets on the screen.

I am encountering an error that states, “setState() or markNeedsBuild() called during build in NotificiationListener”. The Logic i’ve setup involves my MediaProvider updating a variable, ‘hasMore’ to false if the number of documents in the collection matches the number fetched. When hasMore is false, the onNotification method returns false, which should terminate any further media loading until the next app lifecycle.

I expected that once hasMore is set to false (during the build phase apparently), the loading of more media would terminate without triggering any build errors especially because I wrapped it in WidgetsBinding.instance.addPostFrameCallback().

Some of the other solutions I’ve read have suggested that the problem may be because of notifyListeners() which is a form of setState(). However, I have no idea how else I can achieve this functionality without it :/.

ImageGalleryScreen

class ImageGalleryScreen extends StatefulWidget {
  const ImageGalleryScreen({super.key, required this.album});
  final Album album;

  @override
  State<ImageGalleryScreen> createState() => _ImageGalleryScreenState();
}

class _ImageGalleryScreenState extends State<ImageGalleryScreen> {
  late MediaProvider mediaProvider;

  @override
  void initState() {
    mediaProvider = Provider.of<MediaProvider>(context, listen: false);
    mediaProvider.initializeAlbumMedia(widget.album.albumId);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bool hasMore =
        Provider.of<MediaProvider>(context).hasMore[widget.album.albumId] ??
            true;

    return Scaffold(
      appBar: AppBar(
        title: const Text("Image Gallery"),
      ),
      body: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification scrollInfo) {
          final metrics = scrollInfo.metrics;
          if (hasMore && metrics.pixels == metrics.maxScrollExtent) {
            mediaProvider.fetchMoreMedia(widget.album.albumId);
          }

          return hasMore;
        },
        child: ListView(
          children: [
            const Card(
              child: ListTile(
                title: Text("Album card"),
                subtitle: Text("Album details and about info"),
                trailing: Icon(Icons.arrow_forward_ios),
              ),
            ),
            const SizedBox(height: 20),
            Consumer<MediaProvider>(
              builder: (context, provider, child) {
                final mediaList = provider.mediaMap[widget.album.albumId] ?? [];

                if (mediaList.isEmpty) {
                  return const SizedBox(
                    width: double.infinity,
                    child: Center(
                      child: Text("No Images Available."),
                    ),
                  );
                }

                return GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    crossAxisSpacing: 4.0,
                    mainAxisSpacing: 4.0,
                  ),
                  itemCount: mediaList.length,
                  itemBuilder: (context, index) {
                    final media = mediaList[index];

                    return Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        image: DecorationImage(
                          image: CachedNetworkImageProvider(media.downloadUrl),
                          fit: BoxFit.cover,
                        ),
                      ),
                    );
                  },
                );
              },
            ),
            const SizedBox(height: 20),
            Visibility(
              visible: hasMore,
              child: const Center(
                child: CircularProgressIndicator(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

MediaProvider

class ImageProvider extends ChangeNotifier {
  static final ImageProvider _instance = ImageProvider._internal();
  ImageProvider._internal();
  factory ImageProvider() => _instance;

  Map<String, List<Media>> get mediaMap => _mediaMap;
  final Map<String, List<Media>> _mediaMap = {};

  Map<String, int> get mediaCountMap => _mediaCountMap;
  final Map<String, int> _mediaCountMap = {};

  Map<String, bool> get hasMore => _hasMore;
  final Map<String, bool> _hasMore = {};

  final int _limit = 30;
  final Map<String, StreamSubscription<QuerySnapshot>> _subscription = {};
  final Map<String, DocumentSnapshot?> _lastDocInMap = {};

  void initAlbumMedia(String albumId) {
    _getMediaCount(albumId);
    _startMediaSubscription(albumId);
  }

  void _getMediaCount(String albumId) async {
    final snap =
        await FirebaseFirestore.instance.collection('Images').count().get();

    final count = snap.count ?? 0;

    _mediaCountMap[albumId] = count;
    if (count > _limit) {
      _hasMore[albumId] = true;
    }

    notifyListeners();
  }

  void _startMediaSubscription(String albumId) async {
    if (_subscription.containsKey(albumId)) return;

    final subscription = FirebaseFirestore.instance
        .collection('Images')
        .orderBy('dateTime', descending: true)
        .limit(_limit)
        .snapshots()
        .listen((snap) {
      _mediaMap[albumId] =
          snap.docs.map((doc) => Media.fromMap(doc.data())).toList();

      _lastDocInMap[albumId] = snap.docs.isNotEmpty ? snap.docs.last : null;
    });

    _subscription[albumId] = subscription;
    notifyListeners();
  }

  void fetchMoreMedia(String albumId) async {
    final lastDoc = _lastDocInMap[albumId];
    if (lastDoc == null) return;

    final newMedia = await FirebaseFirestore.instance
        .collection('Images')
        .orderBy('dateTime', descending: true)
        .startAfterDocument(lastDoc)
        .limit(9)
        .get()
        .then(
      (snap) {
        if (snap.docs.isEmpty) return null;

        _lastDocInMap[albumId] = snap.docs.last;
        return snap.docs.map((doc) => Media.fromMap(doc.data())).toList();
      },
    );

    if (newMedia == null) {
      _hasMore[albumId] = false;
    } else {
      _mediaMap[albumId]?.addAll(newMedia);
    }

    notifyListeners();
  }
}

When calling provider in the build function you should set listen: false
Example:

bool hasMore = Provider.of<MediaProvider>(context, listen: false).hasMore[widget.album.albumId] ?? true;

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật