In the following code for the scrollcontroller, if i initialise the variable _scrollController as late, then I get issue as LateInitializationError: Field '_scrollController@1084415195' has not been initialized. and If i make it nullable, I get Null check operator used on a null value
class _MyScrollbarState extends State<MyScrollbar> {
ScrollController? _scrollController;
ScrollbarPainter? _scrollbarPainter;
Orientation? _orientation;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateScrollPainter(_scrollController!.position);
});
}
CodePudding user response:
you have to initialize it in the init
class _MyScrollbarState extends State<MyScrollbar> {
ScrollController? _scrollController;
ScrollbarPainter? _scrollbarPainter;
Orientation? _orientation;
@override
void initState() {
super.initState();
_scrollbarPainter = ScrollbarPainter();
_scrollController = ScrollController();
//after this you can now use it anywhere inside your widget
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateScrollPainter(_scrollController!.position);
});
}
State like so:
CodePudding user response:
You need to give them a value so that they dont start as Null. If you give them a default value when you initialize them you should also be able to not use the "?" since now they have a value.
ScrollController _scrollController = ScrollController();
ScrollbarPainter _scrollbarPainter = ScrollbarPainter();