joisberg
joisberg

Reputation: 187

How to call function from another class anywhere

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

Answers (2)

Thea Choem
Thea Choem

Reputation: 795

You should make you method public first and use it like @Jean Lucas.

  • Other way is with mixin:
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

Jean Lucas
Jean Lucas

Reputation: 282

You can make the method static, and call the method with the class name, Like this:

YourClass._checkToken();

Upvotes: 2

Related Questions