在 Flutter 中使用 Future 在异步任务中使用进度条对话框

Use progress bar dialog in async task using Future in Flutter

我想为执行 API 创建通用 class。现在我需要在执行任务时添加进度对话框,完成任务后对话框应该 dismiss.I google 很多但没有得到适当的解决方案所以帮助我实现它。

For Http Client i used dio plugin.

Please help me for adding progress dialog in this class so when i create request using this class it added progress dialog while executing task. i create this type of class in java but now i want to add it in flutter.

HttpRequest.dart

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class HttpRequest {
    void post(BuildContext context,String url, dynamic data, HttpListener listener) {
        Dio dio = new Dio();
        dio.post(url, data: data)
           .then((Response<dynamic> response) {
                  if (response.statusCode == 200) {
                      listener.onSuccess(response.data);
                  } else {
                      listener.onError("Error");
                  }
              })
           .catchError((Exception error) {
              listener.onError(error.toString());
            });
    }
}

abstract class HttpListener {
  void onSuccess(dynamic result);

  void onError(String error);
}

widgets最好显示进度条,不常见类。

使用下面的例子(使用http package):

class HttpRequest {
  final JsonDecoder _decoder = new JsonDecoder();

  Future post(String url, dynamic data) async {
    http.Response response = await http.post(url,body: data);
    if(response.statusCode < 200 || response.statusCode > 300){
      throw new Exception('Faild');
    } else {
      return _decoder.convert(response.body);
    }
  }
}

调用post方法的按钮:

child: MaterialButton(onPressed: () async {
            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }));
            HttpRequest _util = new HttpRequest();
            try{
              var res = await _util.post('someurl',_data);
            } catch(Exception) {
                //Handle Exception
            } finally {
              Navigator.pop(context);
            }
});

我做了一个public包,future_progress_dialog,是package的相反概念。 你想在任务中放置进度对话框。但我尝试了相反的方法,将 Future 任务放入对话框中。

https://pub.dev/packages/future_progress_dialog

使用此包,您可以制作这样的进度对话框。

var result = await showDialog(
    context: context,
    child: FutureProgressDialog(future, 'Loading...'));

希望对您有所帮助。