Flutter ScrollController AssertionError:'_positions. isNotEmpty':关闭路由时,ScrollController未附加到任何滚动视图

xxslljrj  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(141)

我在Flutter应用程序中遇到了一个与ScrollController相关的错误。我有一个屏幕细节,我使用滚动控制器来监视滚动位置。我想在控制器fireWhenCloseQuestionDetails()中触发一个函数,当关闭了ControllerDetailsScreen路由时。为此,我实现了一个自定义的NavigatorObserver。但是,我得到了一个错误:
'_positions. isNotEmpty':ScrollController未附加到任何滚动视图

这是我的银行控制器:

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();
  }
}

我使用自定义的NavigatorObserverQuestionDetailsScreen路由关闭时触发fireWhenCloseQuestionDetails()

class MyNavigatorObserver extends NavigatorObserver {
  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    if (route.settings.name == "/questiondetailsscreen") {
      Future.delayed(Duration.zero, () {
        QuestionBankController().fireWhenCloseQuestionDetails();
      });
    }
  }
}

这个问题似乎与在调用fireWhenCloseQuestionDetails()时创建QuestionBankController的新示例有关。如何确保在关闭路由时使用与QuestionDetailsScreen关联的QuestionBankController的正确示例?

附加信息:

  • 滚动时,滚动监听功能正常工作。
lc8prwob

lc8prwob1#

QuestionBankControlleronClose中调用fireWhenCloseQuestionDetails()怎么样?

@override
void onClose() {
  print("On close");
  fireWhenCloseQuestionDetails();
  questionDetailsScrollCtrl.dispose();
  super.onClose();
}

如果您的QuestionBankController绑定到QuestionDetailsScreen,则可能是这样。

相关问题