Flutter:Futurebuilder无法捕获异常

时间:2020-04-26 11:59:44

标签: flutter dart

我有一个通用类以 ReusableRequestServer 来请求服务器,如果向服务器发送请求时发生错误,则该类将处理一些异常。

ReusableRequestServer

class ReusableRequestServer<T> {
  Future<T> requestServer(FutureOr<T> requestServer()) async {
    try {
      return await requestServer();
    } on FormatException catch (_) {
      throw ConstText.FORMAT_EXCEPTION;
    } on TimeoutException catch (_) {
      throw ConstText.TIMEOUT_EXCEPTION;
    } on SocketException catch (_) {
      throw ConstText.NO_CONNECTION;
    } catch (e) {
      throw e.toString();
    }
  }
}

final reusableRequestServer = ReusableRequestServer();

我有一个简单的get请求,即可从服务器获取移动版本,我也实现了 ReusableRequestServer

获取请求

class MobileVersionApi {
  Future<List<MobileVersionModel>> getNewestMobileVersion() async {
    var result = await reusableRequestServer.requestServer(() async {
      final response = await http
          .get('${appConfig.baseApiUrl}/${appConfig.mobileVersionController}/getNewestVersion')
          .timeout(Duration(seconds: 10));
      final Map<String, dynamic> responseJson = json.decode(response.body);
      if (responseJson["status"] == "ok") {
        List mobileVersionList = responseJson["data"];
        List<MobileVersionModel> result =
            mobileVersionList.map((json) => MobileVersionModel.fromjson(json)).toList();
        return result;
      } else {
        throw responseJson['message'];
      }
    });
    return result;
  }
}

final mobileVersionApi = MobileVersionApi();

但是问题是,即使我以2种方式处理了请求,我也要在futurebuilder中使用它:

  • 创建单独的Future,以避免直接在futurebuilder中传递Future
  • 尝试捕获的处理方式

中没有捕获异常,并导致应用崩溃。

FutureBuilder

Future<List<MobileVersionModel>> mobileVersion;
  Future<List<AppInfoModel>> appInfo;

  @override
  void initState() {
    super.initState();
    final appInfoProvider = Provider.of<AppInfoProvider>(context, listen: false);
    mobileVersion = getMobileVersion();
    appInfo = getAppInfo(appInfoProvider);
  }

  Future<List<MobileVersionModel>> getMobileVersion() async {
    try {
      final result = await mobileVersionApi.getNewestMobileVersion();
      return result;
    } catch (e) {
      globalF.showToast(message: e, isError: true);
      return null;
    }
  }

  Future<List<AppInfoModel>> getAppInfo(AppInfoProvider appInfoProvider) async {
    try {
      final result = appInfoApi.getLogoClient().then((value) {
        appInfoProvider.setAppInfo(value);
        if (value[0].updateTime != appInfoProvider.appInfo.updateTime) {
          globalF.clearCacheApp(); //clears all data in cache.
        }
      });
      return result;
    } catch (e) {
      globalF.showToast(message: e, isError: true);
      return null;
    }
  }

Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer2<GlobalProvider, UserProvider>(
        builder: (_, globalProvider, userProvider, __) => FutureBuilder(
          future: Future.wait([
            mobileVersion,
            appInfo,
          ]),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return LoadingFutureBuilder();
            } else {
              if (snapshot.hasError) {
                return ErrorFutureBuilder(errorText: snapshot.error.toString());
              } else {
                  return Text('Hore');
              }
            }
          },
        ),
      ),
    );
  }

错误

Exception has occurred.
SocketException (SocketException: Failed host lookup: 'xxx.net' (OS Error: No address associated with hostname, errno = 7))

enter image description here 我想念某个地方吗? 谢谢

2 个答案:

答案 0 :(得分:3)

在catch语句中尝试返回Future.error。

例如:

<input type="text">
<ul style="display: none;">
  <li>abc</li>
  <li>efg</li>
  <li>hij</li>
</ul>

答案 1 :(得分:0)

Future<List<MobileVersionModel>> getNewestMobileVersion() async {
try{
    var result = await reusableRequestServer.requestServer(() async {
      final response = await http
          .get('${appConfig.baseApiUrl}/${appConfig.mobileVersionController}/getNewestVersion')
          .timeout(Duration(seconds: 10));
      final Map<String, dynamic> responseJson = json.decode(response.body);
      if (responseJson["status"] == "ok") {
        List mobileVersionList = responseJson["data"];
        List<MobileVersionModel> result =
            mobileVersionList.map((json) => MobileVersionModel.fromjson(json)).toList();
        return result;
      } else {
        throw responseJson['message'];
      }
    });}
catch(e) {
//catch error here
}
    return result;
  }