在颤振中可关闭不应在出现错误时关闭项目

时间:2021-01-22 09:50:53

标签: flutter flutter-layout

除非出现错误,否则下面的代码可以正常工作。即使出现“无网络”或“无法连接到数据库”等错误,当不应删除该项目时,该项目也会从列表中删除。如果出现错误如何处理?

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 个答案:

答案 0 :(得分:1)

Dismissible 小部件为此提供了一个选项,confirmDismiss。它需要一个 Future<bool>。您给它一个返回 Futuretruefalse 方法。因此,根据您的网络操作是否失败,您可以重置 Dismissible

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;
    }
  }
}