0
votes

Hello fellow developers,

For my first Flutter project I need to use a list with sticky headers and infinite scroll. I found a very nice library for this purpose. https://pub.dev/packages/flutter_sticky_header

Final goal is to fetch new items into the list from my database by scrolling further down. For testing purposes I added a button to add a random item to my list. However the UI is not updated when the function is called. I am very new to Flutter. Below my code. How can I update the UI every time an item is added to the list without recreating the widget.

class AppScaffold2 extends StatefulWidget {
  @override
  _AppScaffold2State createState() => _AppScaffold2State();
}

class _AppScaffold2State extends State<AppScaffold2> {

  final CustomScrollView x =  CustomScrollView(
      slivers: new List<Widget>(),
      reverse: false,
    );

    int counter = 0;

  add(Widget w){
    x.slivers.add(w);
  }

  @override
  Widget build(BuildContext context) {
    return DefaultStickyHeaderController(
      child: Scaffold(
        body: Container(child: Column(children: <Widget>[
          Expanded(child: x),
          MaterialButton(
            onPressed: () => fetch(),
            child: Text('add to list')  
          ) 
        ],),)
      ),
    );
  }

  fetch() {
    x.slivers.add(_StickyHeaderList(index: counter));
    counter++;
  }
}

class _StickyHeaderList extends StatelessWidget {
  const _StickyHeaderList({
    Key key,
    this.index,
  }) : super(key: key);

  final int index;

  @override
  Widget build(BuildContext context) {
    return SliverStickyHeader(
      header: Header(index: index),
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, i) => ListTile(
            leading: CircleAvatar(
              child: Text('$index'),
            ),
            title: Image.network(
            "https://i.ytimg.com/vi/ixkoVwKQaJg/hqdefault.jpg?sqp=-oaymwEZCNACELwBSFXyq4qpAwsIARUAAIhCGAFwAQ==&rs=AOn4CLDrYjizQef0rnqvBc0mZyU3k13yrg",
          ),
          ),
          childCount: 6,
        ),
      ),
    );
  }
}
1

1 Answers

0
votes

Try using setState() in fetch Method. like this.

fetch() {
    x.slivers.add(_StickyHeaderList(index: counter));
     setState(() {
        _counter++;
     });  
}```