Home > Software design >  Flutter - How to handle Non-Nullable Instance of widget properties
Flutter - How to handle Non-Nullable Instance of widget properties

Time:01-15

I am new to flutter and currently trying to simple animation on my component, but i keep getting a " Non-Nullable Instance " error, i checked out other video tutorials but theirs worked perfectly while mine keeps throwing errors.

Here's my code.

class HomeScreen extends StatefulWidget {
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {

  Animation<Offset> sbarAnimation;
  AnimationController sbarAnimationController;

  @override

  void initState() {

    super.initState();

    sbarAnimationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 250),
    );

    sbarAnimation = Tween<Offset>(
      begin: Offset(-1, 0),
      end: Offset(0, 0),
    ).animate(
      CurvedAnimation(
        parent: sbarAnimationController,
        curve: Curves.easeInOut,
      ),
    );

  }

And then the code for the widget is below

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(
        color: kBackgroundColor,
        child: Stack(

          children: [
            SafeArea(
              //so the background covers the entire app..
              child: Column(
                children: [
                  HomeScreenNavBar(),                     
                  ExploreCourseList(),
                ],
              ),
            ),

            SlideTransition(

              position: sbarAnimation,   // this is where i call the _animation

              child: SafeArea(
                child: SidebarScreen(),
                bottom: false,  
              ),
            ),
          ],

        ),
      ),
    );
  }
}

below is the errors i keep getting, and most of the solutions i've seen did exactly the same thing, theirs works, but mine is giving this errors.. please what am i supposed to do.

enter image description here

CodePudding user response:

Use late keyword to initialize variables later as you are doing in your initState

late Animation<Offset> sbarAnimation;
late AnimationController sbarAnimationController;

CodePudding user response:

There two way to solve the issue.

  1. Which already answered by Juan Carlos Ramón Condezo, using late keyword, where you must have to initialize it before using anywhere.

  2. You can make the variable nullable. By using '?' After declaring the variable type.

Animation?<Offset> sbarAnimation;
AnimationController? sbarAnimationController;

So, you can check if the variable is null and initialize it when needed.

  •  Tags:  
  • Related