我有一个ScrollController附加到Listview,但是当我滚动它时会引发异常:
@override
initState() {
super.initState();
_mainCategoriesScrollController = ScrollController();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
_mainCategoriesScrollController
.addListener(_mainCatergoriesScrollListener());
});
}
_mainCatergoriesScrollListener() {
if (_mainCategoriesScrollController.offset >=
_mainCategoriesScrollController.position.maxScrollExtent &&
!_mainCategoriesScrollController.position.outOfRange) {
print("reach the bottom");
}
if (_mainCategoriesScrollController.offset <=
_mainCategoriesScrollController.position.minScrollExtent &&
!_mainCategoriesScrollController.position.outOfRange) {
print("reach the top");
}
}
和构建方法
@override
Widget build(BuildContext context) {
_setCurrentMainCategory();
SystemChrome.setEnabledSystemUIOverlays([]);
return Container(
child: Column /*or Column*/ (
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 9,
child: Container(
child: Row(
children: <Widget>[
Expanded(
flex: 3,
child: ListView.builder(
controller: _mainCategoriesScrollController,
shrinkWrap: true,
itemCount: _mainCategories.length,
itemBuilder: (context, index) {
return MainCategoryEntry(
mainCategory: _mainCategories[index],
mainCategorySelected: () {
MyApp.setActivity(context);
setState(() {
currentMainCategory =
_mainCategories[index];
});
},
isSelected: _mainCategories[index] ==
currentMainCategory,
);
}),
),
以下是例外:
════════基础库捕获到异常════════ 调度ScrollController的通知时引发了以下NoSuchMethodError: 方法'call'在null上被调用。 接收者:null 尝试调用:call()
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:207
#2 ChangeNotifier.notifyListeners
package:flutter/…/foundation/change_notifier.dart:207
#3 ScrollPosition.notifyListeners
package:flutter/…/widgets/scroll_position.dart:775
#4 ScrollPosition.setPixels
package:flutter/…/widgets/scroll_position.dart:244
...
The ScrollController sending notification was: ScrollController#7153b(one client, offset 0.7)
════════════════════════════════════════════════════════════════════════════════
有人可以告诉我我做错了什么吗? 非常感谢!
答案 0 :(得分:1)
此行似乎没有调用_mainCategoriesScrollListener方法,而是调用了该方法:
_mainCategoriesScrollController.addListener(_mainCatergoriesScrollListener());
我想当您甚至没有分配客户端时尝试访问_mainCategoriesScrollController方法时,都会发生错误。
即使您尝试添加框架后回调,方法_mainCatergoriesScrollListener()仍会在调用时在initState()中被调用,而不是将其添加到侦听器中。
这可能是错误的原因。
尝试将其更改为:
_mainCategoriesScrollController.addListener(_mainCatergoriesScrollListener);
或
_mainCategoriesScrollController.addListener(() => _mainCatergoriesScrollListener());