progress<T> static method

Future<T> progress<T>(
  1. String message,
  2. Future<T> action(), {
  3. CappProgressType type = CappProgressType.bar,
})

progress method is used to show the progress widget of the action. It can be a spinner, bar, or circle. The message is the message that will be shown in the console. The action is the action that will be executed. The type is the type of the progress widget. The CappProgressType is an enum that contains three types of progress widgets.

Implementation

static Future<T> progress<T>(
  String message,
  Future<T> Function() action, {
  CappProgressType type = CappProgressType.bar,
}) async {
  bool isLoading = true;

  Future<void> showSpinner() async {
    var startTime = DateTime.timestamp();
    String spinner(int index) {
      if (type == CappProgressType.bar) {
        var res = '';
        var back = '█';
        var front = '░';
        for (var i = 0; i < 30; i++) {
          if (i == index) {
            res += front;
          } else {
            res += back;
          }
        }
        return res;
      } else if (type == CappProgressType.circle) {
        var rotating = '⣿⣷⣯⣟⡿⢿⣻⣽⣾';
        return "\t\t" + rotating[(index ~/ 1.5) % rotating.length] + ' ';
      } else if (type == CappProgressType.timer) {
        var time = DateTime.timestamp().difference(startTime);
        return '\t\t${time.inSeconds}.${time.inMilliseconds ~/ 100 % 10}s ';
      } else {
        var res = '|';
        for (var i = 0; i < 30; i++) {
          if (i == index) {
            res += '>';
          } else {
            res += '-';
          }
        }
        res += '|';
        return res;
      }
    }

    int spinnerIndex = 0;

    if (!isWindows) {
      // stdin.lineMode = false;
      // stdin.echoMode = false;
    }

    while (isLoading) {
      console.write('\r$message ${spinner(spinnerIndex)}');
      if (type != CappProgressType.circle) {
        spinnerIndex = (spinnerIndex + 1) % 30;
      } else {
        spinnerIndex++;
      }
      await Future.delayed(Duration(milliseconds: 50));
    }
  }

  var spinnerFuture = showSpinner();

  try {
    T result = await action();
    return result;
  } finally {
    // if (!isWindows) {
    //   stdin.lineMode = true;
    //   stdin.echoMode = true;
    // }
    isLoading = false;
    await spinnerFuture;
    console.write('\r$message\t\tDone!                            \n');
  }
}