Reputation: 119
I would like to create a function to display a snackbar. When i call my function "ErrorPage" nothing is happening. I have no syntax error.
Homepage.dart
import 'package:flutter/material.dart';
import 'package:MyApp/src/screens/error.dart';
ErrorPage(message: "Can't reach the servers, \n Please check your internet connection!!!",);
//Nothing happening
Error.dart
import 'package:flutter/material.dart';
class ErrorPage extends StatelessWidget {
final String message;
const ErrorPage({Key key, this.message = "There was an unknown error." }) : super(key: key);
@override
Widget build(BuildContext context){
print("-------test------");
return SnackBar(
content: Text(message),
duration: Duration(seconds: 3),
);
}
}
Upvotes: 0
Views: 1386
Reputation: 2654
You where almost there this should get you the rest of the way.
//State class
class _ExampleState extends State<Example> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ErrorMessage(message: "There was an unknown error."),
);
}
}
class ErrorMessage extends StatelessWidget {
final String message;
ErrorMessage({this.message});
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text('Show SnackBar'),
onPressed: () {
final snackBar = SnackBar(
duration: Duration(seconds: 3),
content: Text(message),
);
//This is the line you missed
Scaffold.of(context).showSnackBar(snackBar);
},
),
);
}
}
Upvotes: 0
Reputation: 10975
Create a Class under which create a function and then call that function to trigger the snackbar
Point to be noted: you will need to pass GlobalKey
to the snackbar if you want the snackbar to be accessible globally.
GlobalKey
will enable you to show the snackbar on that particular screen.
//for creating a _scaffoldKey
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
//then add the reference of this key to your `scaffold` widget under `key` parameter
Scaffold(
key: _scaffoldKey,
body: //your widgets
);
then create a new Class
Class GlobalValues{
static showSnackbar(_scaffoldKey, String msg) {
_scaffoldKey.currentState.showSnackBar(new SnackBar(
duration: Duration(milliseconds: 1000),
content: new Text(msg),
backgroundColor: Colors.grey[800]));
}
}
call the class from wherever you want like this
GlobalValues.showSnackbar(_scaffoldKey, "your message");
PS: you can use GlobalValues
class to store/ access variables, functions which should be accessible globally into your app.
Upvotes: 1