Flutter学习 — 实现滑动关闭、删除item

效果图一:

在这里插入图片描述

效果图二:

右滑删除第六个item
在这里插入图片描述

效果图三:

左滑删除第4个item
在这里插入图片描述

效果图四:

最后看到,第四项和第六项都被删除了

在这里插入图片描述

代码+注释:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp(
    items: new List<String>.generate(20, (i) => "Item ${i + 1}"),
  ));
}

class MyApp extends StatelessWidget {
  final List<String> items;

  MyApp({Key key, @required this.items}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final title = 'Dismissing Items';

    return new MaterialApp(
      title: title,
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(title),
        ),
        body: new ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];

            return new Dismissible(
              // Each Dismissible must contain a Key. Keys allow Flutter to
              // uniquely identify Widgets.
              /**
               * 每个可豁免项都必须包含一个密钥。 键使Flutter能够唯一标识小部件。
               */
              key: new Key(item),
              // We also need to provide a function that will tell our app
              // what to do after an item has been swiped away.
              /**
               * 我们还需要提供一个可以告诉我们应用程序的功能刷掉物品后该怎么办。
               * onDismissed —— 被解雇
               * direction —— 方位表示:删除方向是左边还是右边,startToEnd 左边,endToStart 右边
               */
              onDismissed: (direction) {
                print(direction);
                items.removeAt(index);    //根据坐标移除具体的item项
                // 显示移除了哪一条item
                Scaffold.of(context).showSnackBar(
                    new SnackBar(content: new Text("$item dismissed")));
              },
              // Show a red background as the item is swiped away
              // 滑动删除item时显示红色背景
              background: new Container(color: Colors.red),
              child: new ListTile(title: new Text('$item')),
            );
          },
        ),
      ),
    );
  }
}

喜欢记得点个赞哟,我是王睿,很高兴认识大家!

更多原理请参考谷歌官网:实现滑动关闭、删除item

猜你喜欢

转载自blog.csdn.net/qq_27494201/article/details/106840913