局部更新有好几种方法,本次使用的是 StatefulBuilder 定义 customState去更新对话框内容
Dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ProgressDialog {
final BuildContext context;
BuildContext? dialogContext;
double _progress = 0.0;
bool _isShowing = false;
StateSetter? mCustomState;
ProgressDialog(this.context, this._progress);
void show() {
_isShowing = true;
showDialog<void>(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(builder: (mDialogContext, customState) {
mCustomState =customState;
dialogContext = mDialogContext;
return AlertDialog(
title: const Text('下载中...'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
LinearProgressIndicator(value: _progress),
Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
child: Text('${(_progress * 100).toStringAsFixed(0)}%'),
),
],
),
);
});
},
);
}
void updateProgress(double progress) {
if (_isShowing && null!=mCustomState) {
(mCustomState!)(() {
_progress = progress;
});
}
}
void hide() {
if (dialogContext != null && _isShowing) {
Navigator.of(dialogContext!).pop();
}
_isShowing = false;
}
}
定义 StateSetter? mCustomState; 去set更新
使用
Dart
final ProgressDialog progressDialog = ProgressDialog(context, 0);
progressDialog.show();
更新进度
progressDialog.updateProgress(progress);
关闭对话框
progressDialog.hide();