Dismissing a Dismissible with Flutter/Dart

后端 未结 5 1206
轻奢々
轻奢々 2021-01-03 17:53

In the majority of the Dismissible examples provided by Flutter, they are dismissing items within a ListView. For example, this.

What I am currently doing is this:

5条回答
  •  星月不相逢
    2021-01-03 18:36

    The error comes when the widget is dismissed but not removed from the tree since the state still contains the dismissed object. Ideal implementation for onDismissed should remove the item and set the new state

    So in your example you would do something like this

    onDismissed: (DismissDirection direction) { dismissPerson(person); }
    

    and in dismissPerson function remove the person and set new state.

    dismissPerson(person) {
        if (_personList.contains(person)) {
        //_personList is list of person shown in ListView
          setState(() {
            _personList.remove(person);
          });
        }
    }
    

    If you refer to the same link posted in the question it now contains proper implementation for dismissible. Adding the relevant snippet of code from the link for convenience

    final Widget card = new Dismissible(
          key: new ObjectKey(cardModel),
          direction: _dismissDirection,
          onDismissed: (DismissDirection direction) { dismissCard(cardModel); },
    
          ....
    
        );
    
    
    void dismissCard(CardModel card) {
        if (_cardModels.contains(card)) {
          setState(() {
            _cardModels.remove(card);
          });
        }
    }
    

提交回复
热议问题