0

I am getting this error in Animated Builder after I enable dart null safety in my flutter because one of my plugin needs it.

return AnimatedBuilder(
            //animation is done here
          animation:_pageController,
          builder: (BuildContext context,Widget widget){
          double value = 1;
            if(_pageController.position.haveDimensions){
              value = _pageController.page! - index;
              value = (1-(value.abs()*0.25)).clamp(0.0, 1.0);
            }
           return Center(
               child: SizedBox(
                 height:Curves.easeInOut.transform(value)*380.0,
                 child: widget,
                 ),
              );
          },

I get error like this:

The argument type 'Center Function(BuildContext, Widget)' can't be assigned to the parameter type 'Widget Function(BuildContext, Widget?)'.

Before I enable dart null safety in pubspec.yaml it was fine.

julemand101
  • 28,470
  • 5
  • 52
  • 48
BestOFBest
  • 43
  • 7

1 Answers1

3

The problem is that the parameter builder in AnimatedBuilder, takes a TransitionBuilder function with the following signature:

Widget TransitionBuilder (
    BuildContext context,
    Widget? child
) 

https://api.flutter.dev/flutter/widgets/TransitionBuilder.html

In Dart 2.12 with null-safety, Widget? means that child can point to an object of the type Widget or null. But in your case you have a method with the signature:

Widget (BuildContext context,Widget widget)

Where Widget means it will always point to a Widget object and can therefore never be null. This signature is therefore not compatible with the required signature for builder.

In your case, the fix is rather simple since you are only using the argument widget to forward it into the child argument in the SizedBox constructor. This constructor has the following signature:

const SizedBox(
    {Key? key,
    double? width,
    double? height,
    Widget? child}
) 

https://api.flutter.dev/flutter/widgets/SizedBox/SizedBox.html

As you can see, child is typed to be Widget? and does therefore allow null as a value. So you can just change the argument type of the method you give as the builder argument to:

          builder: (BuildContext context,Widget? widget){
julemand101
  • 28,470
  • 5
  • 52
  • 48
  • 1
    I typically let the compiler infer the proper types for those, unless it guesses wrong or weird. I save typing (intentional overload) that way. – Randal Schwartz Apr 27 '21 at 15:14