0

I have created a Common class for SnackBar,

class MySnackBar extends StatelessWidget {
  String message;
  int duration;
  BuildContext context;
  MySnackBar(BuildContext context,String message, int duration) {
    this.message = message;
    this.duration = duration;
    this.context = context;
  }

  @override
  Widget build(BuildContext context) {
    return _showSnackBar(this.context, message, duration);
  }

  Widget _showSnackBar(BuildContext context, String message, int duration) {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(message),
      duration: Duration(seconds: duration),
    ));
  }
}

I am calling this class from my other widget like this,

 MySnackBar(
  context,
  _postDetailsModel
    .language.postScreen.bookmarkOwnMessage,
     3);

But it neither displays snackbar nor it throws an error. Can anyone tell me what I am missing or is there is a way to create common snackbar class?

Ravinder Kumar
  • 7,407
  • 3
  • 28
  • 54

2 Answers2

2

You can use flushbar https://pub.dev/packages/flushbar

create customFlushBar

import 'package:flushbar/flushbar.dart';
import 'package:flutter/material.dart';

Flushbar customFlushBar(BuildContext context,String text){
  return Flushbar(
    flushbarPosition: FlushbarPosition.TOP,
    message: text,
    icon: Icon(
      Icons.info_outline,
      size: 28.0,
      color: Colors.blue[300],
    ),
    duration: Duration(seconds: 3),
    leftBarIndicatorColor: Colors.blue[300],
  )..show(context);
}

you can called like this:

customFlushBar(context, 'Sign in failed');
BIS Tech
  • 17,000
  • 12
  • 99
  • 148
1

You should directly use this :

void showSnackBar(BuildContext context, String message, int duration) {
    Scaffold.of(context).showSnackBar(SnackBar(
      content: Text(message),
      duration: Duration(seconds: duration),
    ));
  }

as a method and not as a Widget.

Augustin R
  • 7,089
  • 3
  • 26
  • 54
  • I have tried this already, it throws `Scaffold.of() called with a context that does not contain a Scaffold.` – Ravinder Kumar Nov 26 '19 at 11:23
  • Well there is plenty of threads about it, for exemple see [this one](https://stackoverflow.com/a/51304732/10122791) or [this one](https://stackoverflow.com/a/50452277/10122791) – Augustin R Nov 26 '19 at 11:25
  • But then I will have to pass a scafoldkey every time in the common widget, right? that's kind of kill the purpose. But for now, I think that's the only way to do it. – Ravinder Kumar Nov 26 '19 at 11:43
  • Or as mentioned in the first link, you use a builder to provide a context which contains a Scaffold, it depends how you want to use your snackbar. Personnaly, I switched to Flushbar to avoid those scaffold key problems. – Augustin R Nov 26 '19 at 11:45