Flutter:Firebase Realtime 从对象列表中删除对象

2023-12-03

我正在咨询数据库中注册的所有俱乐部。对于每个俱乐部,我都会将其添加到对象列表中。

当该人删除俱乐部时,会从数据库中删除俱乐部,但在项目列表中未删除,我尝试执行以下操作:

我的 NotClub-Player.dart 类

// FIREBASE CLUBS
List<Club> items = List();
Club item;
DatabaseReference itemRef;

@override
void initState() {
   super.initState();
   item = Club("","","",0,"","","","",0,0,false,"","","","","",false,"","","","","","","","","","","");
   final FirebaseDatabase database = FirebaseDatabase.instance;
   itemRef = database.reference().child(player.player_game_platform).child("CLUB");
   itemRef.onChildAdded.listen(_onEntryAdded);
   itemRef.onChildRemoved.listen(_onEntryRemoved);
   itemRef.onChildChanged.listen(_onEntryChanged);
}

// CLUBS LISTENERS
_onEntryAdded(Event event) {
 setState(() {
   items.add(Club.fromSnapshot(event.snapshot));
 });
}

_onEntryRemoved(Event event) {
 setState(() {
   items.remove(Club.fromSnapshot(event.snapshot));
 });
}

_onEntryChanged(Event event) {
 var old = items.singleWhere((entry) {
   return entry.key == event.snapshot.key;
 });
 setState(() {
   items[items.indexOf(old)] = Club.fromSnapshot(event.snapshot);
 });
}

我的问题: In _onEntryRemoved有一个事件。在这种情况下,它会返回已删除的项目。但它不会从列表中删除相应的项目。

在数据库中,已成功删除。但包含该对象的列表尚未删除它。

这是我的查询

rnew Flexible(
            child: new FirebaseAnimatedList(
              query: FirebaseDatabase.instance.reference().child(player.player_game_platform).child("CLUB").orderByChild("club_name"),
              itemBuilder: (BuildContext context, DataSnapshot snapshot,
                  Animation<double> animation, int index) {
                return new Column(
                  children: <Widget>[
                    new Container(
                      decoration: new BoxDecoration(
                        color: Colors.grey[300],
                      ),
                      child: new ListTile(
                        leading: new CachedNetworkImage(imageUrl: items[index].club_logo, width: 60.0),
                        title: new Text(items[index].club_name, style: new TextStyle(color: Colors.black)),
                        subtitle: new Text("CAPTAIN: "+items[index].club_captain, style: new TextStyle(color: Colors.black)),
                        trailing: new RaisedButton(
                            color: Colors.lightBlue[500],
                            child: new Text("JOIN", style: new TextStyle(color: Colors.white)),
                            onPressed: (){

                            }
                        ),
                      ),
                    ),
                    new Divider(
                      color: Colors.grey[700],
                      height: 0.0,
                    ),
                  ],
                );
              },
            ),
          ),

这是我在 _onEntryRemoved 中得到的- 它返回正确的删除,但删除列表不适用于我。

E/flutter (15214): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (15214): setState() called after dispose(): _join_clubState#a99f1(lifecycle state: defunct, not mounted)
E/flutter (15214): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter (15214): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter (15214): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1098:9)
E/flutter (15214): #1      State.setState (package:flutter/src/widgets/framework.dart:1124:6)
E/flutter (15214): #2      _join_clubState._onEntryRemoved (package:proclubscommunity/Club-Player.dart:807:5)
E/flutter (15214): #3      _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
E/flutter (15214): #4      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:330:11)
E/flutter (15214): #5      _DelayedData.perform (dart:async/stream_impl.dart:578:14)
E/flutter (15214): #6      _StreamImplEvents.handleNext (dart:async/stream_impl.dart:694:11)
E/flutter (15214): #7      _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:654:7)
E/flutter (15214): #8      _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter (15214): #9      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
I/flutter (15214): {club_logo: url_image, club_note: , club_since: , club_three_position: , club_market: false, club_market_color: , club_six_position: , club_premium: false, club_twitter: https://www.twitter.com/, club_first_position: , club_category: 0, club_seven_position: , club_description: , club_copa: 0, club_country: ESPAÑA, club_liga: 0, club_four_position: , club_logo_file_name: club_logo.png, club_plataform: PS4, club_nine_position: , club_captain: RaiiLKilleR, club_name: Barcelona, club_five_position: , club_eight_position: , club_id: 1, club_second_position: , club_logo_folder_name: PS4_Barcelona, club_twitch: https://www.twitch.tv/, club_youtube: https://www.youtube.com/}

将密钥添加到小部件:

            return new Column(
              key: new ObjectKey(items[index].club_name),
              children: <Widget>[
                new Container(
                  decoration: new BoxDecoration(
                    color: Colors.grey[300],
                  ),
                  child: new ListTile(
                    leading: new CachedNetworkImage(imageUrl: items[index].club_logo, width: 60.0),
                    title: new Text(items[index].club_name, style: new TextStyle(color: Colors.black)),
                    subtitle: new Text("Captain: "+items[index].club_captain, style: new TextStyle(color: Colors.black)),
                    trailing: new RaisedButton(
                        color: Colors.lightBlue[500],
                        child: new Text("JOIN", style: new TextStyle(color: Colors.white)),
                        onPressed: (){

                        }
                    ),
                  ),
                ),
                new Divider(
                  color: Colors.grey[700],
                  height: 0.0,
                ),
              ],
            );

_onEntryRemoved()

  _onEntryRemoved(Event event) {
    setState(() {
      print(event.snapshot.value['club_name']);
      items.remove(event.snapshot.value['club_name']);
    });
  }

你的问题在于Club.

当你创建时List<Club> items然后执行items.remove(clubInstance),内部remove方法将使用标准对象 equals 方法实现,它不知道您的密钥。

如果您尝试使用,也会发生同样的情况items.indexOf(clubInstance)。它永远不会“找到”该项目,总是返回-1.

您可以更改您的实现,迭代项目以准确找出您需要删除的项目,然后将其删除,或者您可以实现== and hashCode在俱乐部课上。

如果您打算使用club_name作为关键,添加这两行可能会解决它。

class Club {
  Club({this.club_name});
  final String club_name;

  // this is what you would have to add to your class:
  bool operator ==(o) => o is Club && o.club_name == club_name;
  int get hashCode => club_name.hashCode;
}

注意:这与 flutter 或 firebase 无关,这只是 dart!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Flutter:Firebase Realtime 从对象列表中删除对象 的相关文章

随机推荐

  • HTTP 状态 500 - java.lang.ClassNotFoundException:org.apache.jsp.index_jsp

    我在 Eclipse 中创建了一个 JSP 项目 使用 Tomcat 7 但是当我运行该页面时 我得到一个 ClassnotFoundExcption 在我的项目中 我使用控制器将数据绑定到 JSP 我有一个控制器 一个服务和一个数据对象
  • 致命错误:在非对象上调用成员函数 rowCount()

    我在登录中使用 PDO 按照之前通过 sqli 的指示 并且我已经尝试了以下操作 但是我收到了此致命错误 并且无法弄清楚要提供什么 因此它满足了错误 if query gt rowCount gt 0 session stuff refre
  • 放大二维 UICollectionView

    我创建了一个UICollectionView这是水平和垂直的 它有不同的UICollectionViewCells 一切都布置正确 现在我正在努力做到zoomable The UICollectionViewCells也正确调整了大小 每次
  • 一般解析字符串到日期

    我正在与 Web 服务通信 并且 json 响应中包含日期 问题是这些日期的格式不同 有没有通用的方法来解析这些字符串 您可能应该有一个有序的格式列表来尝试 最好使用乔达时间作为一个比内置 API 好得多的 API 然后依次尝试每个 API
  • Alexa 帐户链接 - “帐户链接凭据无效”

    我正在创建带有帐户链接的 Alexa 技能 我获得了链接授权码并将其兑换为访问令牌 然后 我尝试将所有参数 代码 访问令牌 技能 ID 放入 Alexa Skill Activation API 中 我总是收到一条消息 帐户链接凭据无效 v
  • 更新jar中的.class文件

    我想更新一个 class文件在一个jar与一个新的 最简单的方法是什么 尤其是在 Eclipse IDE 中 本教程详细说明如何更新 jar 文件 jar uf jar file
  • 从 VS2008 升级到 VS2010 后,Web 安装项目删除文件

    我有一个使用 VS2008 构建的 Web 设置项目 我已经将我的解决方案转换为 VS2010 现在当我构建新的安装程序并从 MSI 运行安装时 它安装得很好 然后在最后一步 删除刚刚安装的所有文件 我已将RemovePreviousVer
  • 如何使用inst/extdata中的文件? R 包检查阻止在 R 3.6 中使用 system.file()

    我正在编写 R 包并尝试使用外部文件 我把它放在inst extdata并使用system file extdata file csv package mypackage 在我的函数中加载文件 官方手册只描述了这种获取数据的方式inst e
  • Spring应用程序似乎没有持久化数据

    我正在尝试将一些内容写入我的数据库 但尽管它报告 成功完成请求 但它不起作用 成功后 一切似乎都工作正常 我的控制器正确地重定向了我 Debug DEBUG a d p payment PaymentServiceImpl Requesti
  • 如何让 slickgrid div 根据表格大小调整大小

    我希望我们有一些熟悉 slickGrid 的用户也能看到 StackOverflow 如何使用它 我有一个包含 slickGrid 的 HTML 如下所示 div style width 600px margin 25px 0 0 0 di
  • 领域数据同步不一致

    我遇到一个问题 每次执行相同的查询时 Realm 有时会返回不同的数据 目前我正在使用 SyncAdapter 进行上传 我们的想法是尝试实现离线模式 因此 当用户创建一个项目时 它会被添加到领域数据库中 我通过获取 maxId 并向其添加
  • 实时 Admob 广告突然停止在我的应用中显示

    6 月份 Admob 广告效果非常好 AdMob 向我发送了一封包含验证 PIN 码的信件 以验证我的身份和付款详细信息 七月初左右 几乎所有实时广告都停止在我的应用程序中显示 我仍然发出相同数量的请求 但展示次数太低 我已降至每天 0 0
  • 将 Pandas DataFrame 转换为 JSON

    我将数据存储在 pandas dataframe 中 我想将 tat 转换为 JSON 格式 可以使用以下代码复制示例数据 data Product A B A Zone E A A N E A start 08 00 00 09 00 0
  • 使用 Carthage 构建时如何选择 Swift 工具链

    我正在创建一个 iOS 应用程序并使用 Carthage 来构建外部库 由于我目前使用的库都是 Swift 2 和 Swift 3 所以我有点紧张 因此 我希望拥有一个 Swift 2 分支和一个 Swift 3 分支进行开发 然后在库全部
  • UIPopoverController 太大而 UIPickerView 太小

    我有一个UIPickerView显示在a内UIPopoverController 尺寸UIPickerView are 320x216 由于某种原因 UIPickerView似乎是适当高度的 3 5 并且UIPopoverControlle
  • 如何在 R 中对特定范围内的函数求和?

    这里有三列 indx vehID LocalY 1 2 35 381 2 2 39 381 3 2 43 381 4 2 47 38 5 2 51 381 6 2 55 381 7 2 59 381 8 2 63 379 9 2 67 38
  • 使用 ...spread,但 redux 仍然会抛出有关状态突变的警告

    Redux 在调度时抛出警告 Error A state mutation was detected inside a dispatch in the path roundHistory 2 tickets Take a look at t
  • 仅当外部文件存在时才安装

    我想指示 Inno Setup 仅在某个外部文件存在时才安装该文件 Like so Source d sources SomeDLL dll DestDir app Flags external regserver uninsneverun
  • 此操作无法完成。再试一次 (-22421)

    我正在尝试上传Apple TV应用程序到应用程序商店进行测试 但我遇到了问题 此操作无法完成 再试一次 22421 如下图所示 那我能做什么呢 发生这种情况是因为 Apple 的服务器可能无法正常工作 请稍候或下次尝试 它最终肯定会起作用
  • Flutter:Firebase Realtime 从对象列表中删除对象

    我正在咨询数据库中注册的所有俱乐部 对于每个俱乐部 我都会将其添加到对象列表中 当该人删除俱乐部时 会从数据库中删除俱乐部 但在项目列表中未删除 我尝试执行以下操作 我的 NotClub Player dart 类 FIREBASE CLU