Skip to content

Instantly share code, notes, and snippets.

@Herrytheeagle
Created July 6, 2020 22:32
Show Gist options
  • Save Herrytheeagle/42b74be3efb8c9c2ca562fc38f14c899 to your computer and use it in GitHub Desktop.
Save Herrytheeagle/42b74be3efb8c9c2ca562fc38f14c899 to your computer and use it in GitHub Desktop.
Creating Custom Widget in Flutter
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
//
// Class to generate SnackBar notifications everywhere in the app's codebase
// without being limited to Scafold inherited widgets
//
class NotificationManager {
static BuildContext context;
static Color successBackgroundColor = Colors.black;
static Color errorBackgroundColor = Colors.red;
static generateNewSuccessNotification(String message, {fast: false}) {
SnackBar newNotification = SnackBar(
content: Text(
message,
style: TextStyle(fontSize: 17),
),
backgroundColor: successBackgroundColor,
duration: Duration(milliseconds: fast ? 500 : 1000),
);
if (context == null) {
return;
}
Scaffold.of(context).showSnackBar(newNotification);
}
static generateNewErrorNotification(String message, {fast: false}) {
SnackBar newNotification = SnackBar(
content: Text(
message,
style: TextStyle(fontSize: 17),
),
backgroundColor: errorBackgroundColor,
duration: Duration(milliseconds: fast ? 500 : 1000),
);
if (context == null) {
return;
}
Scaffold.of(context).showSnackBar(newNotification);
}
}
@jogboms
Copy link

jogboms commented Jul 9, 2020

I really do not understand what "without being limited to Scafold inherited widgets" means. It implies once you have this class, you do not need to do showSnackBar when in fact, it does. And its a static class with static methods and a static reference to a BuildContext which can get stale at any time. And yes this implementation would break if the context used cannot find a Scaffold up the tree.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment