当前位置: 首页 > backend >正文

Flutter 弹窗队列管理:实现一个线程安全的通用弹窗队列系统

在开发复杂的 Flutter 应用时,弹窗的管理往往是一个令人头疼的问题。尤其是在多个弹窗需要按顺序显示,或者弹窗的显示需要满足特定条件时,手动管理弹窗的显示和隐藏不仅繁琐,还容易出错。为了解决这个问题,我们可以实现一个通用的弹窗队列管理系统,它能够自动管理弹窗的显示顺序,并且支持条件判断,决定是否显示某个弹窗。

一、需求分析

在实现弹窗队列管理系统之前,我们先明确一下需求:

  1. 支持弹窗队列:能够将多个弹窗按顺序排队,依次显示。
  2. 条件判断:每个弹窗可以指定一个条件函数,只有当条件满足时,弹窗才会显示。
  3. 线程安全:在多线程环境下,确保弹窗队列的操作是安全的。
  4. 通用性:不限制在 StatefulWidget 中使用,可以在任何地方调用。

二、实现思路

为了实现上述需求,我们采用以下设计思路:

  1. 单例模式:使用单例模式管理弹窗队列,确保全局只有一个队列管理实例。
  2. 线程安全:使用 synchronized 包来确保对队列的操作是线程安全的。
  3. 独立函数:提供一个独立的 showQueueDialog 函数,可以在任何地方调用,而不仅仅是 StatefulWidgetState 中。

三、代码实现

以下是完整的代码实现:

1. 弹窗队列管理类

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:synchronized/synchronized.dart';const _defaultTag = 'default_dialog_queue_tag';typedef BSQueueDialogCondition = FutureOr<bool> Function(BuildContext context);
typedef BSQueueDialogShow = FutureOr<void> Function(BuildContext context);class BSQueueDialog {final BSQueueDialogCondition? shouldShow;final BSQueueDialogShow show;const BSQueueDialog({this.shouldShow, required this.show});
}class DialogQueueManager {static final DialogQueueManager _instance = DialogQueueManager._internal();factory DialogQueueManager() => _instance;DialogQueueManager._internal();final _dialogQueue = <String, List<BSQueueDialog>>{};final _displayingDialog = <String, BSQueueDialog>{};final _lock = Lock();Future<void> showQueueDialog<R>({required BuildContext context,BSQueueDialogCondition? shouldShow,required BSQueueDialogShow show,String tag = _defaultTag,}) async {final dialog = BSQueueDialog(shouldShow: shouldShow, show: show);await _lock.synchronized(() async {var queue = _dialogQueue[tag];if (queue == null) {queue = <BSQueueDialog>[];_dialogQueue[tag] = queue;}queue.add(dialog);final displayingDialog = _displayingDialog[tag];if (displayingDialog == null) {_displayingDialog[tag] = dialog;await _showQueueDialog(tag, context);}});}Future<void> _showQueueDialog(String tag, BuildContext context) async {while (true) {await _lock.synchronized(() async {final queue = _dialogQueue[tag];if (queue == null || queue.isEmpty) {_dialogQueue.remove(tag);_displayingDialog.remove(tag);return;}final dialog = queue.removeAt(0);if (!mounted) return;final shouldShow = await dialog.shouldShow?.call(context) ?? false;if (!mounted) return;if (mounted && shouldShow) {_displayingDialog[tag] = dialog;} else {return; // 如果不应该显示,则直接返回}});if (!mounted) return;await dialog.show(context);await _lock.synchronized(() {_displayingDialog.remove(tag);});}}
}

2. 独立的 showQueueDialog 函数

// 独立的 showQueueDialog 函数
Future<void> showQueueDialog<R>({required BuildContext context,BSQueueDialogCondition? shouldShow,required BSQueueDialogShow show,String tag = _defaultTag,
}) async {return DialogQueueManager().showQueueDialog(context: context,shouldShow: shouldShow,show: show,tag: tag,);
}

3. 使用示例

import 'package:flutter/material.dart';void main() {runApp(MyApp());
}class MyApp extends StatelessWidget {Widget build(BuildContext context) {return MaterialApp(title: 'Queue Dialog Example',home: MyHomePage(),);}
}class MyHomePage extends StatelessWidget {Widget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('Queue Dialog Example'),),body: Center(child: ElevatedButton(onPressed: () {showQueueDialog(context: context,shouldShow: (context) async {// 可以在这里添加条件逻辑return true;},show: (context) async {await showDialog(context: context,builder: (context) => AlertDialog(title: Text('Queue Dialog'),content: Text('This is a queued dialog.'),actions: [TextButton(onPressed: () => Navigator.pop(context),child: Text('Close'),),],),);},);},child: Text('Show Queue Dialog'),),),);}
}

四、代码说明

1. 单例模式

使用 DialogQueueManager 类封装队列管理逻辑,确保全局只有一个实例。通过 factory 构造函数和 _internal 私有构造函数实现单例模式。

2. 线程安全

使用 synchronized 包中的 _lock 对象,确保对 _dialogQueue_displayingDialog 的操作是线程安全的。

3. mounted 检查

在每次使用 context 前,都进行 mounted 检查,确保在 widget 被销毁后不会继续操作 context

4. 循环代替递归

使用 while (true) 循环代替递归调用,避免栈溢出问题。

5. 独立的 showQueueDialog 函数

提供了一个独立的 showQueueDialog 函数,可以在任何地方调用,而不仅仅是 StatefulWidgetState 中。

五、总结

通过上述实现,我们构建了一个通用的、线程安全的弹窗队列管理系统。这个系统不仅支持弹窗的按序显示,还支持条件判断,决定是否显示某个弹窗。通过提供独立的 showQueueDialog 函数,我们确保了这个系统可以在任何地方使用,而不仅仅是 StatefulWidgetState 中。这种方式更加灵活,适用于更多的场景,能够有效简化弹窗的管理逻辑,提高代码的可维护性。

http://www.xdnf.cn/news/389.html

相关文章:

  • 学习笔记十七——Rust 支持面向对象编程吗?
  • Yue生成中文歌词
  • Mybatis
  • 数据结构0基础学习堆
  • AcWing 11:背包问题求方案数 ← 0-1背包
  • 与终端同居日记:Linux指令の进阶撩拨手册
  • docker底层原理
  • 如何给云开发生成的智能体增加权限判断
  • AtCoder ABC402 A~D 题解
  • 数据驱动未来:大数据在智能网联汽车中的深度应用
  • Visio导出清晰图片步骤
  • npm 常用操作和配置
  • uv:重新定义Python开发效率的下一代工具链
  • 高可靠 ZIP 压缩方案兼容 Office、PDF、TXT 和图片的二阶段回退机制
  • 【今日三题】打怪(模拟) / 字符串分类(字符串哈希) / 城市群数量(dfs)
  • Cril 截取字段-生成hostname
  • Git命令归纳
  • 少儿编程路线规划
  • Docker Overlay 网络的核心工作(以跨节点容器通信为例)
  • 公务员行测之速算分数记忆检验-无答案版本
  • 《从理论到实践:CRC校验的魔法之旅》
  • Benewake(北醒) TF-NOVA 在通过TTL-USB转接板更改配置教程
  • VUE快速入门-4:简单入门案例
  • eplan许可证无法识别硬件信息
  • if/switch语句初始化功能
  • MySQL内置函数:字符串函数,数值函数,日期函数,流程控制函数
  • 【unity实战】Unity动画层级(Animation Layer)的Sync同步和Timing定时参数使用介绍,同步动画层制作角色的受伤状态
  • 数据结构基本概念
  • 如何导出pip下载的paho-mqtt包
  • 1.了解开发行业