Fade Image.asset when SingleChildScrollView scrolls

1k views Asked by At

I have an image.asset at the top of a Column inside a SingleChildScrollView

I'm trying to achieve that when the users scrolls the scrollView, the image will fade out.

I've tried to to it using the controller property of the scrollView, but I couldn't achieve the opacity change.

Does anyone has an idea what is the most efficient way to do that?

Thank you!

Current Code:

Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                  height: _imageTopPosition + _imageHeight,
                  color: Colors.blue[100],
                ),
                Positioned(
                  top: _customShapeTopPosition,
                  child: MyCustomShape(
                    size: Size(_screenSize.width, _customShapeHeight),
                  ),
                ),
                Positioned(
                  top: _imageTopPosition,
                  right: _imageRightPosition,
                  child: Image.asset( //The image I would like to fade on scroll
                    'assets/images/image.png',
                    width: _imageWidth,
                    height: _imageHeight,
                  ),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: _screenSize.height * 0.05),
            ),
            Text('Some Text'),
          ],
        ),
      ),
    );
1

There are 1 answers

0
Eyal Kutz On BEST ANSWER

Just create an animation controller and update its value according to the scroll controller

full working example:

import 'package:flutter/material.dart';

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> with SingleTickerProviderStateMixin{
  var _controller=ScrollController();
  AnimationController animation;
  @override
  void initState() {
    super.initState();
    animation=AnimationController(vsync:this);
    _controller.addListener(() {
      animation.value=1-_controller.offset/_controller.position.maxScrollExtent;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Center(
        child:Container(
            width: 300,
            height: 300,
            child: SingleChildScrollView(
              controller: _controller,
              child:FadeTransition(
                opacity: animation,
                child:Container(
                  width: 300,
                  height: 600,
                  color: Colors.red,
                )
              )
            ),
          ),
      )
    );
  }
}