Flutter: Equivalent of Animation<double> for a ScrollController

204

Flutter allows the absence of solid field declarations so this can be achieved by not providing a scrollController to a class that is still expecting one. This is done by means of a question mark but requires some further logic.

For example

class MyTestWidget extends StatelessWidget {
  const MyTestWidget({
    this.animator: const AlwaysStoppedAnimation(0),
    this.scrollController,
  });
  final Animation<double> animator;
  final ScrollController? scrollController
}

The addition of the question mark after declaring that scrollController must be a ScrollController also allows it to be null and therefore no value to be provided.

Then in the build method of this Widget "MyTestWidget" you would need to address whether scroll controller is null or not.

Something like

ScrollController _scrollController;
if(scrollController != null){
  _scrollController = scrollController;
}

It adds a bit more code but technically all the flexibility to do whatever you want both with this and any other widget and type will allow for any issue such as this. You can a allow a null field without declaring it then just have to make sure your build code knows what to do with a null value in that field.

Share:
204
RIK
Author by

RIK

Updated on January 04, 2023

Comments

  • RIK
    RIK over 1 year

    With Flutter we can provide an animation with a default value before we have built an AnimationController to act as it's default value.

    This is done with AlwaysStoppedAnimation(double). This can also be assigned whenever an animation does not need to listen to it's controller, hypothetically.

    How do you achieve similar functionality with a ScrollController. We know that ScrollController can be used as the animation property of an AnimatedBuilder and can be used accordingly. But how do you assign an effective AlwaysStoppedScrollController(double) as that property before a ScrollController has been assigned or after it no longer needs to be listened to.