【问题标题】:How to prevent duplicates in my listview? Flutter如何防止在我的列表视图中重复?扑
【发布时间】:2020-05-23 03:13:00
【问题描述】:

因此,我花了几个小时试图弄清楚如何停止向我的 ListView 添加重复项,但没有任何效果。请帮忙。当我将事件列表映射到地点列表图块时,我的列表视图中不断出现重复的地点。

这是我的代码:

@override
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      Expanded(
          child: ListView(
            padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 8.0),
            controller: _scrollController,
            shrinkWrap: true,

                children: PlaceMapState.events
                .map((place) => _PlaceListTile(
                      place: place,
                      // onPlaceChanged: (value) => _onPlaceChanged(value),
                    ))
                .toSet().toList(),
          ),
        ),
    ],

    );

  }

}

这是我检索数据并将其放入事件列表的地方:

 void initPlace(request,requestId){
     var placeId = requestId;
   MarkerId placeIdVal = new MarkerId(placeId);
    //creating new Place
    final Place place = new Place(id: placeIdVal.toString(),

        latLng: LatLng(request['latLng'].latitude, request['latLng'].longitude),
        name: request['title'],
        category: AppState.of(context).selectedCategory,
      );

    setState((){
      events.add(place);
      events.toSet();
    places[placeIdVal]=place;
    print(place);
    });


  }

【问题讨论】:

  • PlaceMapState.events 可能包含重复记录
  • 知道如何防止这种情况发生吗?
  • 你在哪里分配这个值?
  • 我已经编辑了代码并展示了它

标签: listview flutter dart duplicates mapping


【解决方案1】:

覆盖 Place 对象中的 == 运算符

@override
  bool operator ==( other) {
  return  this.id==other.id;
  }

并在添加之前检查列表中已经存在的项目

if (!events.contains(place)) {
 events.add(place);
}

【讨论】:

    【解决方案2】:

    您的.toSet().toList() 不起作用,因为它在内部检查/匹配对象引用,因此您需要按照@Nidheesh 的说明覆盖 == 运算符,以便通过对象的变量差异进行匹配。不要忘记添加字段(基元和类)。

     class Place {
      final String name;
       final int id;
    
       Place({this.name, this.id});
    
       @override
      bool operator ==(Object other) =>
        identical(this, other) ||
        other is Place &&
        runtimeType == other.runtimeType &&
        name == other.name &&
        id == other.id;
    
      @override
      int get hashCode => name.hashCode & id.hashCode;
    
    }
    

    为了更快的实现,你可以试试 Equatable 库:https://pub.dev/packages/equatable

    【讨论】:

      【解决方案3】:
         @override
         bool operator == (other) {
          return this.id == other.id;
         }
      

         if (!events.contains(place)) {
           events.add(place);
          }
      

      【讨论】:

      • 我应该在哪里添加这个?
      • 在setState内
      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2012-11-03
      • 1970-01-01
      • 2020-05-09
      • 2016-08-04
      相关资源
      最近更新 更多