Reputation: 3774
I want to create a ThrowError widget that can be accessed from any page inside my app. Here is what I have done so far:
Parent Widget
My parent widget has a RaisedButton widget that checks if the login info is correct, if not a snackbar message is displayed at the bottom of the page. I have the functionality working with having the RaisedButton widget and snackbar on one file with a GlobalKey assignment. I want to separate the snackbar to its own file so I can use it across my app.
Parent Widget with RaisedButton Widget-
RaisedButton(
hoverColor: Colors.amber,
color: Colors.blueAccent,
child: Text(
'Login',
style: TextStyle(fontSize: 15, color: Colors.white),
),
onPressed: () async {
String status = await _submit();
if(status == "authError") _throwError("Please check your credentials");
if(status == "networkError") _throwError("No Network Connection");
},
),
Parent Widget with _throwError function on the same file as the RaisedButton
void _throwError(String message) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text(message),
duration: Duration(seconds: 3),
));
}
Desired solution
ThrowError Class on a different file -
import 'package:flutter/material.dart';
class ThrowError extends StatelessWidget {
ThrowError({this.context, this.errMessage});
@override
Widget build(BuildContext context) {
Builder(
builder: (context) =>
Scaffold.of(this.context).showSnackBar(SnackBar(
content: Text('Show Snackbar'),
duration: Duration(seconds: 3),
));
);
}
As of now ThrowError class is showing a lot of errors.
Please advise!
EDIT after trying Amine Dakhli answer -
RaisedButton(
color: Colors.blueAccent,
child: Text(
'Login',
style: TextStyle(fontSize: 15, color: Colors.white),
),
onPressed: () async {
String status = await _submit();
if(status == "authError") {
var throwError = new ThrowError();
throwError.showError(context, "test");
}
},
),
And this is the ThrowError class with showError function
import 'package:flutter/material.dart';
class ThrowError {
showError (BuildContext context,String errMessage) {
return Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(errMessage),
duration: Duration(seconds: 3),
)
);
}
}
Upvotes: 0
Views: 701
Reputation: 172
You can put this function in a separate file :
showError (context,message) {
return Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: Duration(seconds: 3),
)
);
}
if you are using a global key as in your case the function should be as follows :
showError (key,message) {
return key.currentState.showSnackBar(
SnackBar(
content: Text(message),
duration: Duration(seconds: 3),
)
);
}
and whenever you want to use it just impor that file and call as follows :
showError(context,'example message') ; in the case of context
showError(yourkeyvariable,'message') ; in the case of a global key
Upvotes: 1