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;