Flutter 弹窗队列管理:支持优先级的线程安全通用弹窗队列系统

在复杂的 Flutter 应用开发中,弹窗管理是一个常见难题。手动管理弹窗的显示顺序和条件判断不仅繁琐,还容易出错。为此,我们实现了一个支持优先级的线程安全通用弹窗队列管理系统。它能够自动管理弹窗的显示顺序,支持条件判断,并且可以灵活地在任何地方调用。

一、需求分析

  1. 支持弹窗队列:按顺序显示多个弹窗。
  2. 条件判断:弹窗显示前可进行条件判断。
  3. 线程安全:确保在多线程环境下操作安全。
  4. 通用性:可在任何地方调用,不限于 StatefulWidget
  5. 优先级支持:支持弹窗优先级,高优先级弹窗优先显示。

二、实现思路

  1. 单例模式:全局只有一个队列管理实例。
  2. 线程安全:使用 synchronized 包确保操作安全。
  3. 优先级排序:弹窗按优先级排序,高优先级先显示。
  4. 独立函数:提供独立的 showQueueDialog 函数,方便调用。

三、代码实现

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;
  final int priority; // 弹窗优先级

  const BSQueueDialog({
    this.shouldShow,
    required this.show,
    this.priority = 0, // 默认优先级为0
  });
}

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,
    int priority = 0, // 弹窗优先级
  }) async {
    final dialog = BSQueueDialog(shouldShow: shouldShow, show: show, priority: priority);
    await _lock.synchronized(() async {
      var queue = _dialogQueue[tag];
      if (queue == null) {
        queue = <BSQueueDialog>[];
        _dialogQueue[tag] = queue;
      }
      queue.add(dialog);
      // 按优先级排序队列,高优先级在前
      queue.sort((a, b) => b.priority.compareTo(a.priority));
      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 函数

Future<void> showQueueDialog<R>({
  required BuildContext context,
  BSQueueDialogCondition? shouldShow,
  required BSQueueDialogShow show,
  String tag = _defaultTag,
  int priority = 0, // 弹窗优先级
}) async {
  return DialogQueueManager().showQueueDialog(
    context: context,
    shouldShow: shouldShow,
    show: show,
    tag: tag,
    priority: priority,
  );
}

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 with priority.'),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: Text('Close'),
                      ),
                    ],
                  ),
                );
              },
              priority: 1, // 设置弹窗优先级
            );
          },
          child: Text('Show Queue Dialog'),
        ),
      ),
    );
  }
}

四、代码说明

  1. 单例模式:通过 DialogQueueManager 类实现单例模式,确保全局只有一个队列管理实例。
  2. 线程安全:使用 synchronized 包中的 _lock 对象,确保对队列的操作是线程安全的。
  3. 优先级排序:弹窗按优先级排序,高优先级的弹窗会优先显示。
  4. 独立函数:提供独立的 showQueueDialog 函数,可在任何地方调用,不限于 StatefulWidget

五、总结

通过上述实现,我们构建了一个支持优先级的线程安全通用弹窗队列管理系统。它不仅支持弹窗的按序显示和条件判断,还支持弹窗优先级,高优先级的弹窗会优先显示。这种方式更加灵活,适用于更多场景,能够有效简化弹窗的管理逻辑,提高代码的可维护性。

你可能感兴趣的:(flutter,flutter,安全,javascript)