In flutter app how put data from header to appBar

546 Views Asked by At

I have ListView and when I'm scrolling the list I want to show data from header which extends beyond the top of the screen in appBar. StickyHeader do not suggest. I specifically need to show information from the header in the appBar I was trying to use scrollcontroller but without success var _controller = ScrollController();

@override
   void initState() {
   super.initState();
  
   // Setup the listener.
   _controller.addListener(() {
     if (_controller.position.atEdge) {
       if (_controller.position.pixels == 0) {
         // You're at the top. 
       } else {
          // You're at the bottom. 
       }
     }
   });
 }

It turns out to show something only when I return to the top of the list. But I can't find a way out of my situation to show information

enter image description here

from each header that is at the top of the list so I want to replace "Not sticky Example" to "Header #0", when it is on top, and when the "Header #2" is on top to show it on appBar

2

There are 2 best solutions below

0
On

Define a variable (or widget) that displays the text in the AppBar:

String appBarTitle = "Initial Value";

Define Scroll Controller:

ScrollController scrollController;

Define a function to act on scroll events (which changes the value of the AppBar title): (Just added one example of the position here which is when reaching the bottom)

  void _scrollListener() {
    if (scrollController.offset != scrollController.position.minScrollExtent &&
        !scrollController.position.outOfRange) {
      // at bottom
      // change the value of the AppBar string
      setState(() {
        appBarTitle = "Something new";
      });
    }
  }

init scroll controller

  @override
  void initState() {
    scrollController = ScrollController();
    scrollController.addListener(_scrollListener);
    super.initState();
  }

Define AppBar in your scaffold as:

AppBar(
        title: Text(appBarTitle),
      )

Using the above, you can make the AppBar title change when the list is scrolled to the bottom - you could then edit _scrollListener to change the value according to your desired logic.

0
On

You can Try out sticky_headers plug in:-

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(itemBuilder: (context, index) {
      return StickyHeader(
        header: Container(
          height: 50.0,
          color: Colors.blueGrey[700],
          padding: EdgeInsets.symmetric(horizontal: 16.0),
          alignment: Alignment.centerLeft,
          child: Text('Header #$index',
            style: const TextStyle(color: Colors.white),
          ),
        ),
        content: Container(
          child: Image.network(imageForIndex(index), fit: BoxFit.cover,
            width: double.infinity, height: 200.0),
        ),
      );
    });
  }
}