Dismissible in flutter shouldn't dismiss item in case of error

Viewed 438

Below code works fine unless there is an error. Even in case of an error like 'no network' or 'cannot connect to database', the item is dismissed from the list when its shouldn't be deleted. How to handle this in case of errors?

class DismissibleListItem extends StatelessWidget {
  const DismissibleListItem({
    this.key,
    this.product,
    this.onTap,
  });

  final Key key;
  final Product product;
  final VoidCallback onDismissed;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return Dismissible(
      background: Container(color: Colors.red),
      key: key,
      direction: DismissDirection.endToStart,
      onDismissed: (direction) => onDismissed(),
      child: ProductListItem(
        product: product,
        onTap: onTap,
      ),
    );
  }
}
1 Answers

The Dismissible Widget has an option for this, confirmDismiss. It expects a Future<bool>. You give it a Future method that returns a true or false. So depending if your network operation fails, or doesn't, you can make the Dismissible reset:

class Issue65842845 extends StatefulWidget {
  @override
  _Issue65842845State createState() => _Issue65842845State();
}

class _Issue65842845State extends State<Issue65842845> {
  List<String> items = [
    'item 1',
    'item 2',
  ];

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index){
        return Dismissible(
          background: Container(color: Colors.red),
          key: Key(items[index].hashCode.toString()),
          direction: DismissDirection.startToEnd,
          confirmDismiss: (direction) => confirmDismiss(items[index]),
          child: Container(
            padding: EdgeInsets.all(6),
            child: Text(items[index]),
            height: 30,
            alignment: Alignment.centerLeft,
          ),
        );
      },
    );
  }

  Future<bool> confirmDismiss(String text) async {
    if(text == 'item 1'){
      // Operation was successful and item was removed from remote server
      // Dismissible is removed
      return true;
    } else {
      // Operation failed and Dismissible is reset
      return false;
    }
  }
}
Related