Flutter创建一个Utility类,但是不能调用异步函数

时间:2018-09-24 09:04:08

标签: asynchronous dart flutter

我的flutter应用程序创建了一个Utility类,并希望在不同的文件/页面中使用Utility类中的函数。但是Utility类的async函数不能被其他文件调用。请帮助解决此问题。

enter image description here

import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'dart:async';

class Utility {

  ConnectivityResult connectivityResult;

  Future<bool> checkConnection() async{
    connectivityResult = await (new Connectivity().checkConnectivity());

    if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)){
      return true;
    } else {
      return false;
    }
  }

  static void showAlert(BuildContext context, String text) {
    var alert = new AlertDialog(
      content: Container(
        child: Row(
          children: <Widget>[Text(text)],
        ),
      ),
      actions: <Widget>[
        new FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "OK",
              style: TextStyle(color: Colors.white),
            ))
      ],
    );

    showDialog(
        context: context,
        builder: (_) {
          return alert;
        });
  }
}

1 个答案:

答案 0 :(得分:2)

在功能上使用static关键字

static Future<bool> checkConnection()

或实例化您的实用程序类