I have a scroll controller in my provider. I want to know if I make the provider ‘autoDispose’, When the provider eventually gets auto disposed, does this dispose the controller within the provider to ? Or do I still need to dispose the scrollController.
Sample code:
import 'package:flutter_riverpod/flutter_riverpod.dart';
final myProvider = Provider.autoDispose(
(ref) {
return MyNotifier();
},
);
class MyNotifier{
final scrollController = ScrollController(initialScrollOffset: 5.0);
}
2
Answers
To make the scrollcontroller disposed when the provider is disposed you should use the provider onDispose method.
The function inside autoDispose is called when the provider is disposed of. Inside the function then you can dispose your controller
You should not be placing anything to do with the view layer into Riverpod providers. Riverpod is for the data layer and the control layer, not the view layer, and a ScrollController or TextEditingController should never be in a Riverpod provider. Those controllers belong in single-widget state, either via a StatefulWidget, or by using flutter_hooks to create a hidden StatefulElement to observe widget lifecycles.