我正在咨询数据库中注册的所有俱乐部。对于每个俱乐部,我都会将其添加到对象列表中。
当人删除club时从数据库中删除club,但在item列表中没有被删除,我尝试过如下操作:
我的 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);
});
}
我的问题: 在 _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 方法实现,它不知道您的 key 。
如果您尝试使用 items.indexOf(clubInstance),也会发生同样的情况.它永远不会“找到”该项目,总是返回 -1 .
您可以更改您的实现,遍历项目以准确找出您需要删除的项目,然后将其删除,或者您可以实现 ==和 hashCode在 Club 类中。
如果您打算使用 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 或火力无关,这只是 Dart !
关于firebase - Flutter:Firebase Realtime 从对象列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919221/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论
我发现ActiveRecord::Base.transaction在复杂方法中非常有效。我想知道是否可以在如下事务中从AWSS3上传/删除文件:S3Object.transactiondo#writeintofiles#raiseanexceptionend引发异常后,每个操作都应在S3上回滚。S3Object这可能吗?? 最佳答案 虽然S3API具有批量删除功能,但它不支持事务,因为每个删除操作都可以独立于其他操作成功/失败。该API不提供任何批量上传功能(通过PUT或POST),因此每个上传操作都是通过一个独立的API调用完成的
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调