Flutter开发中的一些Tips(二)

本文分享了Flutter开发中的四个实用技巧:监听Dialog关闭,避免在初始化时调用addPostFrameCallback,处理emoji删除问题,以及检测键盘是否弹起。针对这些问题,提供了具体的解决方案和代码示例。
摘要由CSDN通过智能技术生成

});

我们可以看看 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;

BuildContextElement的抽象类,你可以认为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){

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值