dart Flutter:阻止从列表中删除数据

tgabmvqs  于 2023-10-13  发布在  Flutter
关注(0)|答案(2)|浏览(127)

我尝试使用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);
}

有谁能告诉我哪里做错了吗

sr4lhrrt

sr4lhrrt1#

add this lib 
https://pub.dev/packages/equatable 

@JsonSerializable()
class Articles  extends Equatable{
  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,
  });

 @override
  List<Object> get props => [name];//  depending on which field you want to remove the list item, replace "name" with your field.

  factory Articles.fromJson(Map<String, dynamic> json) =>
      _$ArticlesFromJson(json);
}
jobtbby3

jobtbby32#

Dart比较两个对象是否为同一示例。你需要覆盖==操作符或者使用像equatable这样的库。

首先删除buildWhen。现在它只会更新(重建)当你添加项目,而不是当你删除它们。

buildWhen: (previous, current) {
          if(previous.length<current.length){
            return true;
          }
          return false;

        },

使用State类来表示状态,因为列表总是相同的,它不会重新生成。之后,调整小部件代码以使用state.articles

class FavouriteState {
 final List<Articles> articles;
 FavouriteState(this.artticles);
}

class FavouriteBloc extends Bloc<FavouriteEvent, FavouriteState> {
  FavouriteBloc() : super(null);
  List<Articles> _articles = [];
  @override
  Stream<FavouriteState> mapEventToState(FavouriteEvent event) async* {
    switch (event.eventType) {
      case EventType.add:
         _articles.add(event.articles);
         yield FavouriteState(_articles);
        break;
      case EventType.delete:
        _articles.remove(event.articles);
        yield FavouriteState(_articles);
        break;
    }
  }
}

urlToImagetitleauthor对比示例

@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,
  });

    @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Articles && runtimeType == other.runtimeType && urlToImage == other.urlToImage &&
      title == other.title && author == other.author;

  @override
  int get hashCode => urlToImage.hashCode ^ title.hashCode ^ author.hashCode;

  factory Articles.fromJson(Map<String, dynamic> json) =>
      _$ArticlesFromJson(json);
}

Equatable包使用示例

@JsonSerializable()
class Articles  extends Equatable{
  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,
  });

 @override
  List<Object> get props => [author, title, description, url, urlToImage, content];

  factory Articles.fromJson(Map<String, dynamic> json) =>
      _$ArticlesFromJson(json);
}

相关问题