Reputation: 187
I have this method for check if token expired. I want to insert this in a class of function and having the ability to call this works anywhere on my application.
Future<http.Response> _checkToken() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var url = kUrlAPI + 'checkToken/';
var response = await http.post(Uri.encodeFull(url),
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer ' + prefs.getString('token'),
});
var convertDataToJson = jsonDecode(response.body);
if(convertDataToJson['code'] == 401){
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => CustomDialog(
pressedAction: () {
//Token expired. Logout and redirect to login page
},
type: 'w',
title: kWarningTitle,
description: kGenericError,
buttonText: kCloseText,
),
);
}
}
Upvotes: 1
Views: 347
Reputation: 795
You should make you method public
first and use it like @Jean Lucas.
mixin YourMixin {
checkToken() {
...
}
}
class YourClass extends StatelessWidget with YourMixin {
const YourClass({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return FlatButton(
onPressed: () {
checkToken();
},
child: Text(""),
);
}
}
Upvotes: 0
Reputation: 282
You can make the method static, and call the method with the class name, Like this:
YourClass._checkToken();
Upvotes: 2