超时抖动后,在按钮单击上重试 http 请求

发布于 2025-01-16 12:31:22 字数 3980 浏览 2 评论 0原文

我创建了这个自定义模态底表,它显示连接超时或没有互联网连接的时间。我已阅读 重试包,它会在 SocketException 或 TimeoutException 上自动重试。当用户点击重试按钮时,如何重试 http 请求?

自定义底表

class CustomModalBottomSheet {
  final typeModal;
  final Function() onTryAgainTap;

  CustomModalBottomSheet({this.onTryAgain, this.typeModal});

  final String connectionTimeOut = 'assets/images/connectiontimeout.png';
  final String noInternet = 'assets/images/nointernet.png';

  noInternetConnectionMBS(context) {
    Size size = MediaQuery.of(context).size;
    showModalBottomSheet(
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(40.0),
        ),
        context: context,
        builder: (BuildContext bc) {
          return Container(
            height: size.height * 0.5,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(40.0),
                topLeft: Radius.circular(40.0),
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height: 20),

                  Stack(
                    children: [
                      Container(
                        height: size.height * 0.3,
                        alignment: Alignment.center,
                        child: Image.asset(
                          typeModal == 'rto' ? connectionTimeOut : noInternet,
                          fit: BoxFit.contain,
                        ),
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: Icon(
                          Icons.close,
                        ),
                      ),
                    ],
                  ),

                  Text(
                      typeModal == 'rto'
                          ? "Connection Time Out"
                          : 'No Internet Connection',
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                  SizedBox(height: 8),
                  Text(
                    "Please Try Again",
                  ),
                  SizedBox(height: 20),
                  SizedBox(
                    width: size.width,
                    child: ElevatedButton(
                        style:
                            ElevatedButton.styleFrom(primary: kSecondaryColor),
                        onPressed: () async {
                          onTryAgainTap();
                          Navigator.pop(context);
                        },
                        child: Text('Try Again')),
                  )
                  //content of modal bottomsheet
                ],
              ),
            ),
          );
        });
  }
}

并在我的 api 服务上调用它,如下所示。

Future<Model> someFunction(
      Model requestModel, BuildContext context) async {
    Map<String, String> requestHeaders = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
    try {
      final response = await http
          .post('$baseURL/url',
              body: json.encode(requestModel), headers: requestHeaders)
          .timeout(Duration(seconds: 30), onTimeout: () {
        CustomModalBottomSheet(onTryAgainTap: null, typeModal: 'rto')
            .noInternetConnectionMBS(context);
        return http.Response('Error', 408);
      });
      if (response.statusCode == 200) {
        
      }
    } on SocketException {
      
      CustomModalBottomSheet(onTryAgainTap: null, typeModal: 'nointernet')
          .noInternetConnectionMBS(context);
    }
} 

I have create this custom Modal Bottom Sheet which showing when Connection time out or No Internet Connection. I have read retry package, that automatically Retry on SocketException or TimeoutException. how do I retry http request just when user tap on try again button?

Custom Bottom Sheet

class CustomModalBottomSheet {
  final typeModal;
  final Function() onTryAgainTap;

  CustomModalBottomSheet({this.onTryAgain, this.typeModal});

  final String connectionTimeOut = 'assets/images/connectiontimeout.png';
  final String noInternet = 'assets/images/nointernet.png';

  noInternetConnectionMBS(context) {
    Size size = MediaQuery.of(context).size;
    showModalBottomSheet(
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(40.0),
        ),
        context: context,
        builder: (BuildContext bc) {
          return Container(
            height: size.height * 0.5,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(40.0),
                topLeft: Radius.circular(40.0),
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height: 20),

                  Stack(
                    children: [
                      Container(
                        height: size.height * 0.3,
                        alignment: Alignment.center,
                        child: Image.asset(
                          typeModal == 'rto' ? connectionTimeOut : noInternet,
                          fit: BoxFit.contain,
                        ),
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: Icon(
                          Icons.close,
                        ),
                      ),
                    ],
                  ),

                  Text(
                      typeModal == 'rto'
                          ? "Connection Time Out"
                          : 'No Internet Connection',
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                  SizedBox(height: 8),
                  Text(
                    "Please Try Again",
                  ),
                  SizedBox(height: 20),
                  SizedBox(
                    width: size.width,
                    child: ElevatedButton(
                        style:
                            ElevatedButton.styleFrom(primary: kSecondaryColor),
                        onPressed: () async {
                          onTryAgainTap();
                          Navigator.pop(context);
                        },
                        child: Text('Try Again')),
                  )
                  //content of modal bottomsheet
                ],
              ),
            ),
          );
        });
  }
}

And call it on my api service like this.

Future<Model> someFunction(
      Model requestModel, BuildContext context) async {
    Map<String, String> requestHeaders = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
    try {
      final response = await http
          .post('$baseURL/url',
              body: json.encode(requestModel), headers: requestHeaders)
          .timeout(Duration(seconds: 30), onTimeout: () {
        CustomModalBottomSheet(onTryAgainTap: null, typeModal: 'rto')
            .noInternetConnectionMBS(context);
        return http.Response('Error', 408);
      });
      if (response.statusCode == 200) {
        
      }
    } on SocketException {
      
      CustomModalBottomSheet(onTryAgainTap: null, typeModal: 'nointernet')
          .noInternetConnectionMBS(context);
    }
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文