Created
July 6, 2020 22:32
-
-
Save Herrytheeagle/42b74be3efb8c9c2ca562fc38f14c899 to your computer and use it in GitHub Desktop.
Creating Custom Widget in Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.