Flutter 如何在任何地方从另一个类调用函数

Flutter 如何在任何地方从另一个类调用函数,flutter,dart,Flutter,Dart,我有这个方法来检查令牌是否过期。我想将其插入一个函数类中,并且能够在我的应用程序的任何地方调用它 Future<http.Response> _checkToken() async { SharedPreferences prefs = await SharedPreferences.getInstance(); var url = kUrlAPI + 'checkToken/'; var response = await http.post(Uri.

我有这个方法来检查令牌是否过期。我想将其插入一个函数类中,并且能够在我的应用程序的任何地方调用它

   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,
        ),
      );
    }

  }
Future\u checkToken()异步{
SharedReferences prefs=等待SharedReferences.getInstance();
var url=kUrlAPI+'checkToken/';
var response=wait http.post(Uri.encodeFull(url)),
标题:{
“内容类型”:“应用程序/json”,
'Authorization':'Bearer'+prefs.getString('token'),
});
var convertDataToJson=jsonDecode(response.body);
if(convertDataToJson['code']==401){
显示对话框(
禁止:错误,
上下文:上下文,
生成器:(BuildContext上下文)=>CustomDialog(
按操作:(){
//令牌已过期。注销并重定向到登录页面
},
类型:“w”,
标题:kWarningTitle,
描述:Kgenericerro,
buttonText:kCloseText,
),
);
}
}

您可以将该方法设置为静态,并使用类名调用该方法,如下所示:

YourClass._checkToken();

您应该首先将方法
公开
,并像@Jean Lucas一样使用它

  • 另一种方法是使用mixin:
mixin您的mixin{
checkToken(){
...
}
}
类YourClass使用YourMixin扩展无状态小部件{
constyourclass({Key}):super(Key:Key);
@凌驾
小部件构建(构建上下文){
返回按钮(
已按下:(){
checkToken();
},
子项:文本(“”),
);
}
}

LoginScreen.\u checkToken()
没有为类型“LoginScreen”定义方法“\u checkToken”。尝试将名称更正为现有方法的名称,或定义一个名为“\u checkToken”的方法。
将方法更改为static,如下所示:static Future\u checkToken()否…不起作用!同样的错误。我使用
函数。_checkToken()
在onPressed()中{}您是否将该方法放在名为Function的类中?