首页 > 其他分享 >Flutter Package: retry

Flutter Package: retry

时间:2023-05-25 14:33:06浏览次数:52  
标签:retry const Package seconds await 重试 Duration Flutter

Flutter package: retry

传送门

This package provides an easy way to retry asynchronous functions. This is often useful to avoid crashing on intermittent errors such as broken connections or temporarily overloaded servers.

这个包提供了一种重试异步函数的简单方法。这通常有助于避免因连接中断或服务器暂时过载等间歇性错误而崩溃。

其实就是当有异常抛出时重试

Google官方的库,但是主页又加了一句

Disclaimer: This is not an officially supported Google product.

免责声明:这不是官方支持的 Google 产品

......

直接使用

simple example:

final response = await retry(
  // Make a GET request
  () => http.get('https://google.com').timeout(Duration(seconds: 5)),
  // Retry on SocketException or TimeoutException
  retryIf: (e) => e is SocketException || e is TimeoutException,
);

访问https://google.com,如果报错且此错误为SocketException或者TimeoutException,则重试

一些主要参数

参数 描述
位置参数 需要调用的异步函数
retryIf 如果满足回调条件则重试,不传则只要是Exception就重试
maxAttempts 最大尝试次数
delayFactor 每次重试的延迟时间
randomizationFactor 每次重试的延迟随机浮动百分比

Using RetryOptions

    RetryOptions options = RetryOptions(
        delayFactor: const Duration(milliseconds: 400),
        randomizationFactor: 0.25,
        maxAttempts: 4,
        maxDelay: Duration(seconds: 20));

    options.retry(
      () async {
        // Make a HTTP request and return the status code.
        final HttpClientRequest request = await client
            .getUrl(Uri.parse('https://www.google.cn'))
            .timeout(const Duration(seconds: 5));
        final HttpClientResponse response =
            await request.close().timeout(const Duration(seconds: 5));
        await response.drain();
        return response.statusCode;
      },
      retryIf: (Exception e) => e is SocketException || e is TimeoutException,
    );

也可以使用RetryOptions来配置参数

加上randomizationFactor每次重试的时间就会上下浮动,比如设置为0.25,maxAttempts设置为8

那么在第一次到第七次重试就会按照以下时间休眠

  • 400 ms +/- 25%
  • 800 ms +/- 25%
  • 1600 ms +/- 25%
  • 3200 ms +/- 25%
  • 6400 ms +/- 25%
  • 12800 ms +/- 25%
  • 25600 ms +/- 25%

完整示例:

Future<void> retryFunction() async {
    // Create an HttpClient.
    final HttpClient client = HttpClient();

    try {
      // Get statusCode by retrying a function
      final int statusCode = await retry(
          () async {
            // Make a HTTP request and return the status code.
            final HttpClientRequest request = await client
                .getUrl(Uri.parse('https://www.google.cn'))
                .timeout(const Duration(seconds: 5));
            final HttpClientResponse response =
                await request.close().timeout(const Duration(seconds: 5));
            await response.drain();
            return response.statusCode;
          },
          // Retry on SocketException or TimeoutException
          retryIf: (Exception e) =>
              e is SocketException || e is TimeoutException,
          maxAttempts: 4,
          delayFactor: const Duration(seconds: 1),
          randomizationFactor: 0.5,
          onRetry: (Exception e) {
            log('onRetry');
          },
          maxDelay: const Duration(seconds: 20));

      // Print result from status code
      if (statusCode == 200) {
        if (kDebugMode) {
          print('google.com is running');
        }
      } else {
        if (kDebugMode) {
          print('google.com is not availble...');
        }
      }
    } finally {
      // Always close an HttpClient from dart:io, to close TCP connections in the
      // connection pool. Many servers has keep-alive to reduce round-trip time
      // for additional requests and avoid that clients run out of port and
      // end up in WAIT_TIME unpleasantries...
      client.close();
    }
  }

标签:retry,const,Package,seconds,await,重试,Duration,Flutter
From: https://www.cnblogs.com/r1cardo/p/17431117.html

相关文章

  • 分析| Flutter 3.10版本有哪些变化?
    Flutter是Google推出的一款用于构建高性能、高保真度移动应用程序、Web和桌面应用程序的开源UI工具包。Flutter使用自己的渲染引擎绘制UI,为用户提供更快的性能和更好的体验。Flutter还提供了丰富的构建工具、库和插件,使开发人员能够更快地构建应用程序。今天就为大家带来Flutter3.......
  • GitlabCI学习笔记之三:GitLabRunner pipeline语法之tags allow_faillure when retry ti
    1.tags用于从允许运行该项目的所有Runner列表中选择特定的Runner,在Runner注册期间,您可以指定Runner的标签。tags可让您使用指定了标签的runner来运行作业,此runner具有ruby和postgres标签。示例给定带有osx标签的OSXRunner和带有windows标签的WindowsRunner,以下作业将在......
  • 直播系统搭建,Flutter实现圆形头像的几种方法
    直播系统搭建,Flutter实现圆形头像的几种方法Flutter实现圆形头像的几种方法使用ClipRRect实现child:ClipRRect( child: Image(  image:AssetImage('images/edge.png'),  fit:BoxFit.cover,  width:100,  height:100, ), borderRadius:BorderRadi......
  • Flutter三棵树系列之详解各种Key
    简介key是widget、element和semanticsNode的唯一标识,同一个parent下的所有element的key不能重复,但是在特定条件下可以在不同parent下使用相同的key,比如page1和page2都可以使用ValueKey(1)。常用key的UML关系图如上,整体上key分为两大类-LocalKey和GlobalKey,这两个key都是抽象类......
  • TEMP_FAILURE_RETRY 宏
    TheGNUlibraryprovidesaconvenientwaytoretryacallafteratemporaryfailure,withthemacroTEMP_FAILURE_RETRY:—Macro:TEMP_FAILURE_RETRY (expression)Thismacroevaluatesexpressiononce,andexaminesitsvalueastypelongint.Ifthevaluee......
  • flutter 使用Get.toName跳转到新页面,返回刷新列表页面
    flutter使用Get.toName跳转到新页面,在新页面执行操作,比如说删除某个对象,需要返回页面刷新列表页面1.Get.toNamed(routes)!.then((value)=>refresh);其中的refresh是执行刷新后的方法2.Get.back(result:'backtorefresh');......
  • Deferred Components-实现Flutter运行时动态下发Dart代码 | 京东云技术团队
    导读DeferredComponents,官方实现的Flutter代码动态下发的方案。本文主要介绍官方方案的实现细节,探索在国内环境下使用DeferredComponents,并且实现了最小验证demo。读罢本文,你就可以实现Dart文件级别代码的动态下发。一、引言DeferredComponents是Flutter2.2推出的功能,依赖于......
  • Flutter一天一控件之ListTile
    ListTile简介Flutter中的ListTile控件是一种常用的列表项控件,它可以用于显示列表中的每一个项,通常包含标题、副标题、图标等内容。ListTile控件的外观和行为类似于Android中的ListView中的列表项。一个简单的ListTile示例:ListTile(leading:Icon(Icons.person),//左侧图标......
  • flutter dio自定义http client
    finaldio=Dio();DiogetMyDio(){initAdapter();dio.options.headers={'apiKey':'xxxxx'};dio.options.connectTimeout=constDuration(seconds:15);dio.options.receiveTimeout=constDuration(seconds:15);di......
  • Flutter入门资料推荐
    前言群里很多入门小白不知道如何入门Flutter,水一篇文章简单介绍下本人学习过程中一些参考资料,方便Flutter小白少走弯路。非权威,推荐只针对本人经验来的说,大佬们不喜勿喷!资料列表书籍类第二版序|《Flutter实战·第二版》dio作者写滴,资料还是有保证,介绍比较全面,Flutter内容基......