gpt4 book ai didi

flutter : Futurebuilder not catch exception

转载 作者:行者123 更新时间:2023-12-03 03:22:45 30 4
gpt4 key购买 nike

我有通用类来请求名为 的服务器可重用请求服务器 ,如果在向服务器发出请求时发生错误,该类将处理一些异常。

可重用的请求服务器

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请求从服务器获取移动版本,我也实现了 可重用请求服务器 也。

获取请求
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();


但是问题是当我在futurebuilder中使用请求时,即使我已经以两种方式处理了它:
  • 创建分离的 Future ,避免在futurebuilder
  • 中直接传递future
  • 用 Try Catch 处理

  • 中未捕获的异常if snapshot.hasError 并使应用程序崩溃。

    future builder
    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
    我错过了什么地方?
    谢谢

    最佳答案

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

    catch (e){
    return Future.error(e.toString());
    }

    关于 flutter : Futurebuilder not catch exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61440363/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com