【发布时间】:2021-03-03 05:22:08
【问题描述】:
我正在尝试使用bloc 创建最喜欢的新闻列表,现在如果我想添加到最喜欢的列表中,它确实会发生,但是如果我想删除它,那么列表没有得到更新,所以它不会从用户界面。
我的集团逻辑,
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});
}
用户界面部分,
在此屏幕中,当我添加到收藏夹时,它会显示我已添加的卡片列表,然后我使用 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);
}
那么谁能告诉我我在这里做错了什么?
【问题讨论】:
-
你能分享模型类吗
-
@gowthamanC 好的,我已经在问题中添加了我的模型类
标签: flutter dart flutter-bloc