Search code examples
flutterdartflutter-layoutflutter-listview

Flutter: I wants to show message to the user only if the user reaches end of the ListView


Below is my code but it is showing the SnackBar frequently when I reach the bottom of ListView. It also shows the SnackBar on the pages also but I wants to show it only one time how to do that.

final snackBar = SnackBar(content: const Text('Yay! A SnackBar!'));

 Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  itemCount: docs.length,
                  itemBuilder: (context, index) {
                    final doc = docs[index];
                    print(doc);
                    //_checkController();
                    _scrollController.addListener(() {
                      if (_scrollController.position.pixels ==
                          _scrollController.position.maxScrollExtent) {
                        ScaffoldMessenger.of(context).showSnackBar(snackBar);
                      } else {
                        if (_scrollController.position.pixels !=
                            _scrollController.position.maxScrollExtent) {
                          return null;
                        }
                      }
                    });
                    return builddoc(doc);
                  },

Solution

  • Because you are assigning new listeners every time item builder calls.

    put this code in ititState so it just called once.

                      _scrollController.addListener(() {
                          if (_scrollController.position.pixels ==
                              _scrollController.position.maxScrollExtent) {
                            ScaffoldMessenger.of(context).showSnackBar(snackBar);
                          } else {
                            if (_scrollController.position.pixels !=
                                _scrollController.position.maxScrollExtent) {
                              return null;
                            }
                          }
                        });