Brightcode
Brightcode

Reputation: 768

How to call snackbar from one page to multiple pages - flutter

I have this snackbar code where I can show a message to the user

 final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

 showSnackBar(String text, Color color) {
    final snackBar = new SnackBar(
      content: CustomText(
        text: text,
        color: white,
        weight: FontWeight.bold,
        size: 17,
      ),
      duration: Duration(seconds: 4),
      backgroundColor: color,
    );
    _scaffoldKey.currentState.showSnackBar(snackBar);
  }

and inside my scaffold I added my key as key: _scaffoldKey, And then I can call the snackbar using the code showSnackBar("Some Text", Colors.red) But the problem I have is that I have to add this code in every page/screen that am using

So what I want is to create a separate dart file and add this code then be able to import and use in any page I want. So please how do I do That.

N/B: Please Ignore the CustomText In my code cause that's a model-ish I use

Upvotes: 0

Views: 1271

Answers (3)

Godwin Mathias
Godwin Mathias

Reputation: 524

Here is a clean approach: NOTE: you're going to depend on context

Create my_util.dart and:

extension MyUtils on BuildContext {

  void showErrorMessage(String error, {int? duration}) {
    ScaffoldMessenger.of(this)
      ..hideCurrentSnackBar()
      ..showSnackBar(
        SnackBar(
          content: Row(
            children: [
              Icon(Icons.warning_rounded, color: Colors.white),
              SizedBox(
                width: 10,
              ),
              Flexible(
                child: Text(
                  error,
                  overflow: TextOverflow.clip,
                ),
              ),
            ],
          ),
          dismissDirection: DismissDirection.startToEnd,
          behavior: SnackBarBehavior.fixed,
          duration: Duration(seconds: duration ?? 2),
        ),
      );
  }
}



Import my_util.dart


   ElevatedButton(onPressed: () {
      context.showErrorMessage('Convert your money to naira to continue');
     });

I hope it helps.

Upvotes: 2

Ayyaz Shair
Ayyaz Shair

Reputation: 620

I came up with a simple solution, you can make a static function for snackbar and use it all through the app just by passing a scaffoldkey and the message like following

    class MyMessageHandler {
      static void showMySnackBar(var _scaffoldKey, String message) {
      _scaffoldKey.currentState.showSnackBar(SnackBar(
         backgroundColor: Colors.green,
         content: Text(message ?? ""),
         duration: Duration(seconds: 2),
          ));
         }
      }

and then call it with any event triggering widget like following

  RaisedButton(
  onPressed: () =>
      MyMessageHandler.showMySnackBar(_scaffoldKey, "message"),
  child: Text("Show my snackbar"),
  );

Now you have your custom snackbar, you can modify it according to your design :)

Upvotes: 1

Yilmaz Guleryuz
Yilmaz Guleryuz

Reputation: 9735

here is snippet extracted from my apps.

step.1: create a dart file called common_dialogs.dart

import 'package:flutter/material.dart';
// ...
theSnackBar(context, String message) {
  return SnackBar(
    duration: Duration(seconds: 2),
    content: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(
          width: 260.0,
          child: Text(
            message,
            overflow: TextOverflow.fade,
            softWrap: false,
          ),
        ),
        Icon(Icons.error),
      ],
    ),
    backgroundColor: Colors.orangeAccent,
  );
}

step.2: any widget that needs those widgets, then it must import 'common_dialogs.dart'; first

step.3: now you can call show snack bar like this

_scaffoldKey.currentState 
      ..hideCurrentSnackBar()
      ..showSnackBar(theSnackBar(context, message));

Upvotes: 0

Related Questions