Solved: AppBar and ListView.length

Question

Asked by none on December 15, 2021 (source).

The title: of AppBar is Text. If the Body has ListView that was made out of Stream. How can the Text in the title reflect the ListView number of items.

    build(BuildContext context) {
      return Scaffold(
      appBar:AppBar(title: generateTitle()) // <-- how to pass the snapshot.requiredData.length into here?
      body: StreamBuilder(
        stream: theStream();
        builder:(BuildContext context, AsyncSnapshot<List<AnObject>> snapshot) {
          return ListView.builder(
            itemCount: snapshot.requireData.length,            
            itemBuilder: (context, index) =>
              CardFromAnObject(snapshot,snapshot.requireData[index], context),
          )
        }
      )
   )
}

Answer

Question answered by Bhumika P (source).

You can add addPostFrameCallback to count your data items and then use totalItem in Appbar.

    build(BuildContext context) {
      return Scaffold(
      appBar:AppBar(title: generateTitle())
      body: StreamBuilder(
        stream: theStream();
        builder:(BuildContext context, AsyncSnapshot<List<AnObject>> snapshot) {

              if (latchRefresher != snapshot.requireData.length){//init the field on declare to latchRefresher =-1
                                      SchedulerBinding.instance
                                          .addPostFrameCallback((_) => setState(() {
                                        totalItem = snapshot.data.length;
                                       latchRefresher = snapshot.requireData.length;//this will cause only on change to request a refresh
                                      }));
              }
          return ListView.builder(
            itemCount: snapshot.requireData.length,            
            itemBuilder: (context, index) =>
              CardFromAnObject(snapshot,snapshot.requireData[index], context),
          );
        }
      ));}
DART FLUTTER LISTVIEW STREAM
SHARE: