How to animate the color of AppBar on scroll?

Issue

How can I animate the color of my SliverAppBar as I scroll through the CustomScrollView?

Scaffold(
  body: CustomScrollView(
    controller: _scrollController,
    slivers: [
      SliverAppBar(...),
      buildBody(),
    ],
  ),
);

Solution

try the following code:

ScrollController _scrollController;
Color _appColor = Colors.black;

  @override
  void initState() {
    super.initState();

  _scrollController= ScrollController()..addListener(() { 
    if(_scrollController.position.pixels == 0){
      _appColor = Colors.black;
      setState(() {});
    }
    else if(_scrollController.position.pixels == 100){
      _appColor = Colors.red;
      setState(() {});
    }
  });
  }

Scaffold(
  body: CustomScrollView(
    controller: _scrollController,
    slivers: [
      //put _appColor to appbar backgroundColor
      SliverAppBar(),
      buildBody(),
    ],
  ),
);

Answered By – Jim

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.