Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

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

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,
      ),
    );
  }
}
question from:https://stackoverflow.com/questions/65842845/dismissible-in-flutter-shouldnt-dismiss-item-in-case-of-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...