You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

删除分类后黑屏问题求助(Flutter客户端+Laravel后端)

问题分析与解决方案

你遇到的删除分类后客户端黑屏的问题,核心原因是错误地弹出了Categories页面而非关闭确认对话框,导致路由栈异常。以下是具体排查和修复步骤:

1. 核心问题定位

在Categories页面的deleteCategory方法中,你使用了State的context执行Navigator.pop(context),这会直接将当前的Categories页面从路由栈中弹出,而不是关闭确认对话框。如果路由栈中只剩Categories页面,弹出后就会出现黑屏。

// 原代码:错误地弹出Categories页面
Future deleteCategory(Function callback, Category category) async{
  await callback(category);
  if (!mounted) return;
  Navigator.pop(context); // 这里的context是Categories页面的context
}

2. 修复步骤

步骤1:修改deleteCategory方法,传递对话框context

调整方法参数,接收确认对话框的context,先关闭对话框再执行删除操作:

Future deleteCategory(BuildContext dialogContext, Function callback, Category category) async{
  // 先关闭确认对话框
  Navigator.pop(dialogContext);
  // 执行删除逻辑
  await callback(category);
  // 不需要弹出Categories页面,保持在当前页面更新列表
}

步骤2:调用方法时传递对话框的context

在确认按钮的onPressed中,传递showDialog builder的context(即对话框的context):

TextButton(
  onPressed: () => deleteCategory(context, provider.deleteCategory, category),
  child: const Text('Confirm')
),

3. 潜在问题优化(可选但推荐)

为了确保categories.remove(category)能正确找到并移除对象,需要在Category类中重写==运算符和hashCode:

class Category {
  final int id;
  final String name;

  Category({required this.id, required this.name});

  factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      id: json['id'],
      name: json['name'],
    );
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Category &&
          runtimeType == other.runtimeType &&
          id == other.id;

  @override
  int get hashCode => id.hashCode;
}

修复后流程说明

  1. 点击删除按钮,弹出确认对话框
  2. 点击确认,先关闭对话框
  3. 执行API删除操作,更新本地categories列表并通知UI重建
  4. Categories页面保持显示,列表自动更新(删除最后一项时显示空白列表,而非黑屏)

内容的提问来源于stack exchange,提问作者zaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:40:34