So I have a PageController appended to a PageView, I set the value of the PageController while declaring it globally but I came across an error, Null check operator used on a null value
, so I called the initState
method and initialised the value of my controller there but nothing changed, I have looked at another question on stack overflow, with the same error but I don't think it is related to my problem. Anyway, here is the code and the error:
Error:
The following _CastError was thrown building:
Null check operator used on a null value
When the exception was thrown, this was the stack:
#0 ScrollPosition.minScrollExtent (package:flutter/src/widgets/scroll_position.dart:136:49)
#1 _PagePosition.page (package:flutter/src/widgets/page_view.dart:386:22)
#2 PageController.page (package:flutter/src/widgets/page_view.dart:179:21)
#3 _HomeState.build.<anonymous closure>.<anonymous closure> (package:.../screens/home.dart:160:43)
#4 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:455:22)
...
Code:
PageController _pageController = PageController(initialPage: 1, viewportFraction: 0.8);
@override
void initState() {
super.initState();
_pageController = PageController(initialPage: 1, viewportFraction: 0.8);
}
@override
Widget build(BuildContext context) {
// other code...
return PageView.builder(
controller: _pageController,
itemCount: (list.length + 1),
scrollDirection: Axis.vertical,
onPageChanged: (val) {
setState(() {});
},
itemBuilder: (context, index) {
if (index == list.length) {
// Widget
}
else {
// other code
_pageController.page.toInt() != (index) ? (Widget) : (Widget) // line where the error occurs
}
},
);
}
Sometimes the error resolves by itself, and returns the PageView perfectly, but that's rare, happens only a few times.
EDIT: I forgot to mention but, once I start scrolling, the problem resolves