Flutter: Draggable和DragTarget 可拖动小部件

class _MyHomeState extends State<MyHome> {

  List<Map<String, String>> _data1 = [
    {'title': 'a'},
    {'title': 'b'}
  ];
  Set<Map<String, String>> _data2 = Set();

  @override
  Widget build(BuildContext context) {

    Widget myChip(e) {
      return Chip(
        avatar: CircleAvatar(
          child: Text(e['title'][0]),
        ),
        label: Text(e['title']),
      );
    }

    Widget myGreyBox(w) {
      return Material(
        child: w,
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo'),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            height: 280,
            decoration: BoxDecoration(
              color: Colors.grey[200],
            ),
            child: Wrap(
              children: _data1.map((e) {
                return Draggable<Map>(
                  data: e,
                  child: myChip(e),
                  childWhenDragging: Opacity(
                    opacity: 0.5,
                    child: myChip(e),
                  ),
                  feedback: myGreyBox(myChip(e)),
                );
              }).toList(),
            ),
          ),
          SizedBox(
            height: 50,
          ),
          DragTarget<Map>(
            onWillAccept: (v) => true,
            // 当在此拖动目标上放置可接受的数据时调用
            onAccept: (value) {
              print('Accept: $value');
              setState(() {
                _data2.add(value);
                _data1.remove(value);
              });
            },
            // 当拖动此目标的给定数据片段离开目标时调用
            onLeave: (value) {
              print('Leave: $value');
            },

            builder: (context, candidates, rejects) {
              return Container(
                constraints: BoxConstraints(
                  minHeight: 280,
                ),
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                ),
                child: Column(
                  children: _data2.map((e) {
                    return ListTile(
                      leading: CircleAvatar(
                        child: Text(e['title'][0]),
                      ),
                      title: Text(e['title']),
                      trailing: IconButton(
                        onPressed: () {
                          setState(() {
                            _data2.remove(e);
                          });
                        },
                        icon: Icon(Icons.delete_outline),
                      ),
                    );
                  }).toList(),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}

猜你喜欢

转载自www.cnblogs.com/ajanuw/p/10926334.html