});
我们可以看看 mounted
在源码中是什么
BuildContext get context => _element;
StatefulElement _element;
/// Whether this [State] object is currently in a tree.
///
/// After creating a [State] object and before calling [initState], the
/// framework “mounts” the [State] object by associating it with a
/// [BuildContext]. The [State] object remains mounted until the framework
/// calls [dispose], after which time the framework will never ask the [State]
/// object to [build] again.
///
/// It is an error to call [setState] unless [mounted] is true.
bool get mounted => _element != null;
BuildContext
是Element
的抽象类,你可以认为mounted
就是 context
是否存在。那么同样在回调中用到 context
时,也需要判断一下mounted
。比如我们要弹出一个 Dialog
时,或者在请求接口成功时退出当前页面。BuildContext
的概念是比较重要,需要掌握它,错误使用一般虽不会崩溃,但是会使得代码无效。
本问题详细的代码见:[点击查看](()
2.监听Dialog的关闭
问题描述:我在每次的接口请求前都会弹出一个Dialog
做loading提示,当接口请求成功或者失败时关闭它。可是如果在请求中,我们点击了返回键人为的关闭了它,那么当真正请求成功或者失败关闭它时,由于我们调用了Navigator.pop(context)
导致我们错误的关闭了当前页面。
那么解决问题的突破口就是知道何时Dialog的关闭,那么就可以使用 WillPopScope
拦截到返回键的输入,同时记录到Dialog的关闭。
bool _isShowDialog = false;
void closeDialog() {
if (mounted && _isShowDialog){
_isShowDialog = false;
Navigator.pop(context);
}
}
void showDialog() {
/// 避免重复弹出
if (mounted && !_isShowDialog){