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,
);
- snackbar.dart
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
3
Answers
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?
To display a Snackbar when you reach the end of articles, you can use the
Scaffold.of(context).showSnackBar()
method.For Example:
This will display the Snackbar when the articles list is empty. You can customize the Snackbar by setting its content, duration, and other properties.
You can use ScaffoldMessanger to show snackbr as below,