fluttersnackbar

How to Show Snackbar within ScaffoldMessenger as Widget in Flutter?


I have a new use case for Snackbar. I was asked to make a program which reads articles from API and it will show Snackbar when it reaches the end of articles. I meant, all examples of using Snackbar always use a button in order to display it. How can I display Snackbar when I reach the end of articles?

This is my code:

    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        if (state.hasReachedMax) {
          return const SnackbarPage(); //<= This one
        } else {
          if (index >= state.posts.length) {
            return const BottomLoader();
          } else {
            return PostListItem(post: state.posts[index]);
          }
        }
      },
      itemCount: state.hasReachedMax ? state.posts.length : state.posts.length + 1,
      controller: _scrollController,
    );
    import 'package:flutter/material.dart';

    class SnackbarPage extends StatelessWidget {
      const SnackbarPage({super.key});

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: ScaffoldMessenger(  //Error here
            child: SnackBar(
              content: const Text('Reach the end of posts'),
              action: SnackBarAction(
                onPressed: () {
                  //if action button is pressed
                },
                label: 'Close',
              ),
            ),
          ),
        );
      }
    }

I got error: Null check operator used on a null value

It seems that ScaffoldMessenger cannot be used as a Widget as return.

References: Snackbar ScaffoldMessenger


Solution

  • I think you can use the Scaffold.of method to access the Scaffold ancestor of your ListView.builder, and then call the showSnackBar method on the Scaffold to display the Snackbar.

    Would something like this work?

    return ListView.builder(
      itemBuilder: (BuildContext context, int index) {
        if (state.hasReachedMax) {
          Scaffold.of(context).showSnackBar(
            SnackBar(
              content: const Text('Reach the end of posts'),
              action: SnackBarAction(
                onPressed: () {
                  //if action button is pressed
                },
                label: 'Close',
              ),
            ),
          );
          return Container();
        } else {
          if (index >= state.posts.length) {
            return const BottomLoader();
          } else {
            return PostListItem(post: state.posts[index]);
          }
        }
      },
      itemCount: state.hasReachedMax ? state.posts.length : state.posts.length + 1,
      controller: _scrollController,
    );