Getting error as Null check operator used on a null value when variable is made nullable

Issue

In the following code for the scrollcontroller, if i initialise the variable _scrollController as late, then I get issue as
LateInitializationError: Field ‘[email protected]’ 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);
    
    
        });
      }

Solution

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

Answered By – john

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published