riverpod
riverpod copied to clipboard
Pagination approach at pub example won't dispose fetchPackagesProvider of a page even if it's out of screen
The pagination approach at pub
example (Also mentioned by Remi at FlutterVikings before) won't dispose fetchPackagesProvider of a page even if it's out of screen.
i.e: If you scroll down and load second page then scroll to the top, all PackageItem
of the second page will be disposed but the corresponding provider fetchPackagesProvider
of that page won't be disposed.
The reason is that we're using ref
of the main SearchPage
widget to fetch a page: https://github.com/rrousselGit/riverpod/blob/4dda346ad6b749c8493299d7e44b38d5ba7e45a7/examples/pub/lib/search.dart#L86
A potential solution is to wrap PackageItem
with Consumer but that's not possible with declarative pagination as we need to return null
to end the pagination.
Here's a minimal sample that clarifies the issue:
@riverpod
String test1(Test1Ref ref, int index) {
ref.onDispose(() {
print('dispose test1 at $index');
});
return index.toString();
}
@riverpod
String test2(Test2Ref ref, int index) {
ref.onDispose(() {
print('dispose test2 at $index');
});
return index.toString();
}
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
cacheExtent: 0,
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
ref.watch(test1Provider(index));
return Consumer(
builder: (context, ref, child) {
ref.watch(test2Provider(index));
return ListTile(title: Text(index.toString()));
},
);
},
),
),
],
),
),
);
}
}