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

Flutter弹窗中RadioListTile无法切换状态问题求助

问题解决:RadioListTile无法切换选中状态

核心原因

你的BookModule类没有重写==运算符和hashCode方法。Flutter的Radio组件通过比较value和groupValue的相等性来判断选中状态,默认的对象比较是引用比较——每次从Firestore快照解析出的BookModule都是新实例,即使数据完全相同,引用也不一样,导致selectedBook和当前_book永远不相等,Radio按钮无法正确切换状态。

解决步骤

1. 重写BookModule的==和hashCode

在你的BookModule类中添加以下代码,用文档唯一的id作为比较依据:

class BookModule {
  final String id;
  final String title;
  // 你的其他字段...

  BookModule({required this.id, required this.title, /* 其他参数 */});

  factory BookModule.fromJSON(DocumentSnapshot doc) {
    return BookModule(
      id: doc.id, // 确保这里正确获取文档ID
      title: doc['title'],
      // 解析其他字段
    );
  }

  // 重写相等性判断
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is BookModule &&
          runtimeType == other.runtimeType &&
          id == other.id;

  // 重写哈希值
  @override
  int get hashCode => id.hashCode;
}

2. 初始化selectedBook的初始值

在_CreateNewBillPageState的initState方法中,将selectedBook初始化为传入的widget.book,确保打开对话框时初始选中状态正确:

@override
void initState() {
  super.initState();
  selectedBook = widget.book;
}

3. 修复StreamBuilder的空数据判断

原代码中当快照有数据但文档数量为0时,显示CircularProgressIndicator是错误的,改为显示无数据提示:

if (snapshot.hasData) {
  final docs = snapshot.data!.docs;
  if (docs.length > 0) {
    // 构建ListView的代码保持不变
  } else {
    return const Center(child: Text('No books found'));
  }
} else if (snapshot.hasError) {
  return const Center(child: Text('Failed to load books'));
} else {
  return const Center(child: CircularProgressIndicator());
}

完成以上修改后,RadioListTile就能正常切换选中状态了。

内容的提问来源于stack exchange,提问作者陈思睿

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:54:59