我尝试使用bloc
创建最喜欢的新闻列表,现在如果我想添加到最喜欢的列表,它确实会发生,但如果我想删除它,那么列表不会更新,所以它不会从UI中删除。
我的集体逻辑,
class FavouriteBloc extends Bloc<FavouriteEvent, List<Articles>> {
FavouriteBloc() : super(null);
List<Articles> articles = [];
@override
Stream<List<Articles>> mapEventToState(FavouriteEvent event) async* {
switch (event.eventType) {
case EventType.add:
articles.add(event.articles);
yield articles;
break;
case EventType.delete:
articles.remove(event.articles);
yield articles;
break;
}
}
}
事件类,
enum EventType {add, delete}
class FavouriteEvent{
Articles articles;
EventType eventType;
FavouriteEvent.add({this.articles,this.eventType});
FavouriteEvent.remove({this.articles,this.eventType});
}
UI部分,
在这个屏幕中,当我添加到收藏夹时,它会显示我添加的卡片列表,然后我使用onTap
将其从列表中删除,但这并没有发生
class FavouriteScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(),
body: BlocBuilder<FavouriteBloc, List<Articles>>(
buildWhen: (previous, current) {
if(previous.length<current.length){
return true;
}
return false;
},
builder: (context, newsList) {
if (newsList == null) {
return Center(
child: Text(
week7.Strings.noFav,
style: Theme.of(context).textTheme.headline6,
),
);
}
return ListView.builder(
itemCount: newsList.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
BlocProvider.of<FavouriteBloc>(context).add( //<--- this is how I'm trying to remove
FavouriteEvent.remove(
articles: Articles(
urlToImage: newsList[index].urlToImage,
title: newsList[index].title,
author: newsList[index].author
),
eventType: EventType.delete));
},
child: Card(...),
);
});
},
),
);
}
}
模型类,
@JsonSerializable()
class Articles {
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
DateTime publishedAt;
String content;
Articles({
this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content,
});
factory Articles.fromJson(Map<String, dynamic> json) =>
_$ArticlesFromJson(json);
}
有谁能告诉我哪里做错了吗
2条答案
按热度按时间sr4lhrrt1#
jobtbby32#
Dart比较两个对象是否为同一示例。你需要覆盖
==
操作符或者使用像equatable这样的库。首先删除
buildWhen
。现在它只会更新(重建)当你添加项目,而不是当你删除它们。使用State类来表示状态,因为列表总是相同的,它不会重新生成。之后,调整小部件代码以使用
state.articles
。urlToImage
、title
、author
对比示例Equatable
包使用示例