I use Riverpod as state management in my web app. I am trying to build an AppBar that scrolls automatically to certain parts of a ListView.
I created a ScrollController as a provider for this purpose.
final scrollControllerProvider = StateProvider<ScrollController?>((ref) => ScrollController());
To scroll, I use .animateTo
from the AppBar actions.
ref.read(scrollControllerProvider)!.animateTo(
0,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
The scrolling works, but it throws an exception
The provided ScrollController is currently attached to more than one ScrollPosition.
I have read that I should be using a StatefulWidget. However, using a ConsumerStatefulWidget I can’t create the ScrollController using Riverpod, because I need to initiate it in initState()
and I can’t access to a provider from it. Is possible to have these two elements together?
2
Answers
ScrollController
is aChangeNotifier
class, instead ofStateProvider
, useChangeNotifierProvider
, keep in mind if you can’t attach it to multiple scrollable.maybe we can make it into new class, create a like
forceDispose()
method :but since i am not sure how you use this, and where you will dispose it in some state,either we can’t initialize it in some initState(), lets just leave the provider autoDispose its self:
i test it, i create New Consumer to Imitate Another Widget, but you must sure the actuall scrollable still mounted :
You have access to
ref
inside any function that resides in theConsumerStatefulWidget
. So, you can simply call your provider ininitState()
function and it should behave normally