首页 > 解决方案 > showDialog 在颤动中多次显示

问题描述

我正在使用 showDialog 创建自己的 progressDialog,它可以工作,但会多次显示 progressDialog。我正在发布我的代码,我该怎么做才能根据进度值更新我在 CircularProgress Indicator 上的进度?

编辑:我也尝试过使用 StateBuilder,但得到了相同的结果。我知道问题是 showDialog 多次调用,我该如何防止它并更新进度?

调用示例函数:

void uploadAndShowProgress() {
    for (double i = 0; i < 50; i += 10) {
      Future.delayed(Duration(seconds: 1));
      _dialog.showOrUpdateProgressDialog((i*0.01));
    }
}

ProgressDialog 类:

import 'package:flutter/material.dart';
import 'package:snapik/common/utils/mediaquery.dart';

class ProgressDialog {
  bool isShowing;
  double currentProgress;
  BuildContext context;

  ProgressDialog(
      {@required BuildContext context,
      bool isShowing,
      double currentProgress}) {
    this.context = context;
    this.isShowing = isShowing ??= false;
    this.currentProgress = currentProgress ??= 0.0;
  }

  void showOrUpdateProgressDialog(double progress) {
    if (!isShowing) {
      isShowing = true;
    }

    final _dialog = await showDialog(
    context: context,
    barrierColor: Colors.black54,
    builder: (context) => StatefulBuilder(
          builder: (context, setState) {
            setState(() {
              currentProgress = progress;
            });
            return ProgressWidget(
              progress: currentProgress,
            );
          },
        ),
    barrierDismissible: true);
  }

  void hideProgressDialog() {
    if (isShowing) {
      Navigator.pop(context);
    }
  }
}

class ProgressWidget extends StatelessWidget {
  final double progress;

  ProgressWidget({@required this.progress});

  Widget build(BuildContext context) {
    return Container(
      color: Colors.black54,
      margin: EdgeInsets.all(8),
      width: MediaQueryUtils(context).width * 0.85,
      height: MediaQueryUtils(context).height * 0.15,
      child: Card(
        child: Row(
          children: [
            Flexible(
              child: Container(
                padding: EdgeInsets.all(8),
                child: CircularProgressIndicator(
                  value: progress,
                ),
              ),
              flex: 1,
            ),
            Flexible(
              child: Container(
                margin: EdgeInsets.all(4),
                child: Text(
                  'uploading...',
                  style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: Theme.of(context).textTheme.headline5.fontSize),
                ),
              ),
              flex: 4,
            ),
          ],
        ),
      ),
    );
  }
}

标签: flutterflutter-layout

解决方案


推荐阅读