skip to Main Content

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

2

Answers


  1. you have to initialize it in the initState like so:

    class _MyScrollbarState extends State<MyScrollbar> {
         late  ScrollController _scrollController;
       late  ScrollbarPainter _scrollbarPainter;
        
       late Orientation _orientation;
        
          @override
          void initState() {
            super.initState();
            
        _scrollbarPainter = ScrollbarPainter();
        _scrollController = ScrollController();
        _orientation = Orientation();
    
        //after this you can now use it anywhere inside your widget 
        
            WidgetsBinding.instance.addPostFrameCallback((_) {
        
                _updateScrollPainter(_scrollController!.position);
        
        
            });
          }
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search