i want create SnackBar
for reusable(globally)
i already created but its only for 1 page , i don't know how to create reusable.
below code:
import 'package:flutter/material.dart';
class SnackBarMain extends StatefulWidget {
@override
_SnackBarMainState createState() => _SnackBarMainState();
}
class _SnackBarMainState extends State<SnackBarMain> {
final globalKey = GlobalKey<ScaffoldState>();
String title = 'SnackBar';
@override
Widget build(BuildContext context) {
return Scaffold(
key: globalKey,
resizeToAvoidBottomPadding: false,
appBar: AppBar(
centerTitle: true,
title: Text(title),
),
body: Center(
child: RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.purple)),
onPressed: () => snackBarMsg(context),
color: Colors.purple,
textColor: Colors.white,
child: Text("SnackBar",
style: TextStyle(fontSize: 18)),
),
),
);
}
snackBarMsg(BuildContext context) {
final sb = SnackBar(
elevation: 0.0,
//behavior: SnackBarBehavior.floating,
content: Text('SnackBar Bottom Message'),
duration: new Duration(seconds: 5000000),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
),
//backgroundColor: Colors.redAccent,
action: SnackBarAction(
textColor: Color(0xFFFAF2FB),
label: 'OK',
onPressed: () {},
),
);
globalKey.currentState.showSnackBar(sb);
}
}
so any one please give me example for this
We can create flutter snackbar in our application by calling its constructor and there is only one required property to create a snackbar which is content. Usually, we will use a Text widget for content since we need to show some message to the user. We can use other widgets instead if we want.
then you can simply call the Get. snackbar() to show the snackbar where you want it to be displayed. You can use this package when you don't have the context too. Save this answer.
Just create a public class and put your custom functions inside, here you go for example:
//Custom class in project directory
class CustomWidgets {
CustomWidgets._();
static buildErrorSnackbar(BuildContext context, String message) {
Scaffold.of(context)
.showSnackBar(
SnackBar(
content: Text("$message"),
),
);
}
}
// This is any page in your project
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
// Always create body with Builder method so you can
// get exact context to pass
body: Builder(
builder: (context) =>
Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: (){
CustomWidgets.buildErrorSnackbar(context,"Your message here");
},
child: Text('Display SnackBar'),
),
),
),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With