I'm encountering an error in my Flutter application related to a ScrollController. I have a QuestionDetailsScreen where I'm using a ScrollController to monitor the scroll position. I want to trigger a function in my controller fireWhenCloseQuestionDetails() when the QuestionDetailsScreen route is closed. To do this, I've implemented a custom NavigatorObserver. However, I'm getting an error:
'_positions.isNotEmpty': ScrollController not attached to any scroll views
Here's my QuestionBankController:
class QuestionBankController extends GetxController {
ScrollController questionDetailsScrollCtrl = ScrollController();
@override
void onInit() {
questionDetailsScrollCtrl = ScrollController();
questionDetailsScrollCtrl.addListener(_onScroll);
super.onInit();
}
void _onScroll() {
// This function will be called every time the scroll position changes
print("Scroll position: ${questionDetailsScrollCtrl.position.pixels}");
}
void fireWhenCloseQuestionDetails() {
print("Fire");
print(questionDetailsScrollCtrl.position.pixels);
}
@override
void onClose() {
print("On close");
questionDetailsScrollCtrl.dispose();
super.onClose();
}
}
I'm using a custom NavigatorObserver to trigger fireWhenCloseQuestionDetails() when the QuestionDetailsScreen route is closed:
class MyNavigatorObserver extends NavigatorObserver {
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route.settings.name == "/questiondetailsscreen") {
Future.delayed(Duration.zero, () {
QuestionBankController().fireWhenCloseQuestionDetails();
});
}
}
}
It seems like the issue might be related to creating a new instance of QuestionBankController when calling fireWhenCloseQuestionDetails(). How can I ensure I'm using the correct instance of QuestionBankController associated with my QuestionDetailsScreen specifically when closing the route?
Additional Information:
- The scroll listening functionality is working correctly while scrolling.