Flutter拖拽交互插件drag_like的使用

Flutter拖拽交互插件drag_like的使用

概述

drag_like 是一个用于实现左滑右滑/喜欢、不喜欢特效的Flutter插件。该插件具有以下功能:

  1. 支持划出事件回调,通知上层是左边划出还是右边划出。
  2. 支持滑动进度回调。
  3. 支持第二层widget缩放完成回调,缩放完成时刷新数据。
  4. 支持手指抬起回调。
  5. 支持手速检测,速度超过指定值后,卡片将会划出屏幕,已解决手速不准确问题。
  6. 具有null安全特性。
  7. 支持控制左右划出。
  8. 支持设置滑出动画执行时长。
  9. 支持控制器左右划出时,自定义回调参数。

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  drag_like: ^last_version

效果图

使用方法

主要参数说明

  • dragController: 控制器,用于手动触发左右滑动。
  • duration: 动画执行时间。
  • child: 第一个子组件,可以是任何可滑动的Widget。
  • secondChild: 第二个子组件,当第一个子组件被滑出时显示。
  • allowDrag: 是否允许拖拽。
  • screenWidth: 屏幕宽度。
  • outValue: 滑出边界值。
  • dragSpeed: 手速检测阈值。
  • onChangeDragDistance: 滑动距离变化回调。
  • onOutComplete: 滑出完成回调。
  • onScaleComplete: 缩放完成回调。
  • onPointerUp: 手指抬起回调。
  • onCancel: 取消操作回调。

示例代码

import 'dart:ui';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  DragController _dragController = DragController();
  List data = [
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn20%2F170%2Fw1024h1546%2F20180318%2Fa00d-fyshfur3814572.jpg&refer=http%3A%2F%2Fn.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613903060&t=651082a2ee0be03315c114381adaea8d',
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn1.itc.cn%2Fimg8%2Fwb%2Frecom%2F2016%2F05%2F19%2F146364216575228138.JPEG&refer=http%3A%2F%2Fn1.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614001788&t=3727c8bd4ef9b45d3749fa42a6f28081',
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201302%2F17%2F20130217172444_rKtvc.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614001866&t=a54e01b85f08ceaff5511f8def64ef38',
    'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1220965489,466788603&fm=26&gp=0.jpg',
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp4.qhimg.com%2Ft01613ae824dd1edf73.jpg&refer=http%3A%2F%2Fp4.qhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614001866&t=4eee5185802274b50430200acd6fcbec',
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2Fmn01%2F022319225536%2F1Z223225536-4.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614001866&t=dc5b44cf1f3581c1a787d1e4673ebc57',
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2017-12-11%2F5a2e3dc01ae8c.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614001866&t=f2eaf54e9c947e66a4ac87ccc4faa8dc',
    'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fphoto.meifajie.com%2Fpictures%2F2018-05%2F180507_152555_31502.jpg&refer=http%3A%2F%2Fphoto.meifajie.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614001866&t=7ffe32272026d19d863d4566ba675f31',
  ];

  List imagelist = [];

  void loaddata() async {
    await Future.delayed(Duration(milliseconds: 2000));
    imagelist.addAll(data);
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    loaddata();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('DragLike Example'),
        ),
        body: Center(
          child: Container(
            width: double.infinity,
            height: double.infinity,
            child: Stack(
              children: [
                Container(
                  padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
                  child: DragLike(
                    dragController: _dragController,
                    duration: Duration(milliseconds: 520),
                    allowDrag: true,
                    child: imagelist.length <= 0
                        ? Text('加载中...')
                        : ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: TestDrag(src: imagelist[0])),
                    secondChild: imagelist.length <= 1
                        ? Container()
                        : ClipRRect(
                            borderRadius: BorderRadius.circular(10),
                            child: TestDrag(src: imagelist[1])),
                    screenWidth: 375,
                    outValue: 0.8,
                    dragSpeed: 1000,
                    onChangeDragDistance: (distance) {
                      /// {distance: 0.17511112467447917, distanceProgress: 0.2918518744574653}
                      // print(distance.toString());
                    },
                    onOutComplete: (type) {
                      /// left or right
                      print(type);
                    },
                    onScaleComplete: () {
                      imagelist.remove(imagelist[0]);
                      if (imagelist.length == 0) {
                        loaddata();
                      }
                      setState(() {});
                    },
                    onPointerUp: () {},
                    onCancel: () {
                      print('取消了');
                    },
                  ),
                ),
                Positioned(
                  left: 0,
                  bottom: MediaQuery.of(context).viewInsets.bottom + 50,
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        ElevatedButton(
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(
                              Colors.blueAccent
                            ),
                            elevation: MaterialStateProperty.all(0),
                            shape: MaterialStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(25),
                                side: BorderSide(color: Colors.transparent),
                              )
                            ),
                            padding: MaterialStateProperty.all(
                             EdgeInsets.all(20)
                            ),
                          ),
                          child: Text('Left', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 30)),
                          onPressed: () async {
                            if (imagelist.length > 0) _dragController.toLeft(completeTag: 'custom_left');
                          }
                        ),
                        ElevatedButton(
                          style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all(
                              Colors.pinkAccent
                            ),
                            elevation: MaterialStateProperty.all(0),
                            shape: MaterialStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(25),
                                side: BorderSide(color: Colors.transparent),
                              )
                            ),
                            padding: MaterialStateProperty.all(
                             EdgeInsets.all(20)
                            ),
                          ),
                          child: Text('Right', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 30)),
                          onPressed: () async {
                            if (imagelist.length > 0) _dragController.toRight(completeTag: 'custom_right');
                          }
                        ),
                      ],
                    ),
                  )
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class TestDrag extends StatefulWidget {
  final String src;
  const TestDrag({Key? key, required this.src}) : super(key: key);

  @override
  _TestDragState createState() => _TestDragState();
}

class _TestDragState extends State<TestDrag> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.grey,
      child: Stack(
        children: [
          Positioned.fill(child: Image.network(
            widget.src,
            fit: BoxFit.cover,
          )),
          // Text(widget.src)
        ],
      ),
    );
  }
}

回调方法

onOutComplete

当卡片滑出屏幕时触发的回调,参数为滑出方向(left 或 right):

onOutComplete: (type) {
  /// left or right
  print(type);
},

onScaleComplete

当卡片缩放完成时触发的回调:

onScaleComplete: () {
  imagelist.remove(imagelist[0]);
  if (imagelist.length == 0) {
    loaddata();
  }
  setState(() {});
},

onChangeDragDistance

当卡片滑动距离变化时触发的回调:

onChangeDragDistance: (distance) {
  /// {distance: 0.17511112467447917, distanceProgress: 0.2918518744574653}
  print(distance.toString());
},

onPointerUp

当手指抬起时触发的回调:

onPointerUp: () {
  
},

onCancel

当操作取消时触发的回调:

onCancel: () {
  print('取消了');
},

控制器

通过控制器可以手动触发左右滑动:

_dragController.toLeft(completeTag: 'custom_left');
_dragController.toRight(completeTag: 'custom_right');

更多关于Flutter拖拽交互插件drag_like的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter拖拽交互插件drag_like的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用drag_like插件来实现拖拽交互的代码案例。drag_like是一个Flutter插件,它允许你实现类似于微信聊天中的拖拽删除或排序功能。

首先,你需要在你的pubspec.yaml文件中添加drag_like依赖:

dependencies:
  flutter:
    sdk: flutter
  drag_like: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

接下来,我们来看一个简单的例子,展示如何使用drag_like插件实现一个可拖拽排序的列表。

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Drag Like Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> items = List.generate(20, (index) => "Item $index");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Drag Like Demo'),
      ),
      body: DragLikeList(
        data: items,
        itemBuilder: (context, index, item) {
          return ListTile(
            title: Text(item),
            trailing: Icon(Icons.drag_handle),
          );
        },
        onDragEnd: (fromIndex, toIndex) {
          if (fromIndex != toIndex) {
            setState(() {
              final String item = items.removeAt(fromIndex);
              items.insert(toIndex, item);
            });
          }
        },
      ),
    );
  }
}

在这个例子中,我们创建了一个简单的Flutter应用,其中包含一个可拖拽排序的列表。以下是代码的关键部分:

  1. 依赖导入:确保你已经在pubspec.yaml文件中添加了drag_like依赖。
  2. 数据准备:在_MyHomePageState类中,我们创建了一个包含20个字符串项的列表。
  3. UI构建:在build方法中,我们使用DragLikeList组件来构建列表。DragLikeList接受以下参数:
    • data:列表数据。
    • itemBuilder:用于构建列表项的回调函数。
    • onDragEnd:拖拽结束时的回调函数,用于处理列表项的重新排序。

itemBuilder回调函数用于构建每个列表项,这里我们简单地使用了ListTile组件,并在右侧添加了一个拖拽手柄图标。

onDragEnd回调函数在拖拽结束时被调用。我们通过fromIndextoIndex参数获取拖拽的起始和结束位置,然后使用setState方法更新列表数据,以实现列表项的重新排序。

这个简单的例子展示了如何使用drag_like插件来实现一个基本的拖拽排序功能。你可以根据需要进一步定制和扩展这个例子。

回到顶部