Custom SnackBar Type Class for Reusability - flutter

Viewed 300



Hello, I'd love to know how to create a custom Class of Type SnackBar for reusability - so I can be allowed to use it in ScaffoldMessenger.of(context).showSnackBar() method that ONLY accepts SnackBar type & not StatelessWidget


I wanted a reusable SnackBar so I created this custom SnackysnackBar extending from StatelessWidget

class SnackysnackBar extends StatelessWidget {
  const SnackysnackBar({Key? key, required this.snackText}) : super(key: key);
  final String snackText;

  @override
  Widget build(BuildContext context) => SnackBar(
    content: Text(
      '$snackText',
      textAlign: TextAlign.center,
    ),
    backgroundColor: Colors.green[300],
  );
}

thinking I would be able to reuse it in my :

ElevatedButton(
      onPressed: () {
        ScaffoldMessenger.of(context).showSnackBar(SnackysnackBar(snackText: "I'm a snack Text look at me"));
      }, 

turns out it only accepts a parameter of type 'SnackBar'

  • so I thought I would extend a class from SnackBar like this right ?
class SnackysnackBar extends SnackBar {
  final String snackText;
  
const SnackysnackBar({Key? key, required this.snackText,}) : super(key: key, this.content,);
  @override
  Widget build(BuildContext context) => SnackBar(
        content: Text(
          '$snackText',
          textAlign: TextAlign.center,
        ),
        backgroundColor: Colors.green[300],
      );
}

but it seems like it's not the right approach - or is it ?



I'm getting this error : "The named parameter 'content' is required, but there's no corresponding argument."



1 Answers

Simply create a function

SnackBar getSnackBar(String snackText) => SnackBar(
      content: Text(
        '$snackText',
        textAlign: TextAlign.center,
      ),
      backgroundColor: Colors.green[300],
    );

and pass it around

ElevatedButton(
      onPressed: () {
        ScaffoldMessenger.of(context).showSnackBar(getSnackBar("I'm a snack Text look at me"));
      }, 
Related