Flutter拖拽调整大小插件draggable_resizer的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter拖拽调整大小插件draggable_resizer的使用

插件功能

draggable_resizer插件允许在二维轴上无缝地拖动小部件,并同时进行缩放和旋转。

功能包括:

  • 无缝拖动小部件
  • 拖动时允许缩放
  • 拖动时允许旋转

使用步骤

Step1: 添加插件依赖

将插件添加到您的 pubspec.yaml 文件中:

draggable_resizer: [latest_version]
Step2: 导入包

在您的 [your_file].dart 文件中导入插件:

import 'package:draggable_resizer/draggable_resizer.dart';
Step3: 调用可拖动组件

以下代码示例展示了如何水平从左到右拖动组件:

const DraggableResizer(
    draggerColor: Colors.white,
    axis: Axis.horizontal,
    direction: Direction.leftToRight)
Step4: 监听状态变化

您可以监听值的变化(从1到100,从左到右):

const DraggableResizer(
    draggerColor: Colors.white,
    axis: Axis.horizontal,
    direction: Direction.leftToRight,
    onValueChange: ((val) => setState(() {
        print("值已更改为 $val");
    })))
Step5: 更改为您自定义的小部件

前往 example/lib/main.dart 文件查看所有示例。请参阅下一节中的图片。

Step6: 运行!

在终端中使用以下命令运行项目:

flutter run

示例

最初,这个插件是作为“调整滑块”的替代品而创建的,但后来发现了多种用途。以下是示例Gif/Mp4文件:

示例图片

完整示例Demo

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

void main() {
  runApp(const MyHomePage());
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double volume = 1.0;
  String ratingImg = "assets/rating/emoji3.png";
  double ratingVal = 25.0;
  double speakerVal = 20.0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: const Color(0xFF222222),
        body: SafeArea(
          child: Center(
            child: SingleChildScrollView(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // EXAMPLE 1: VOLUME BOOSTER
                _heading("示例 1"),
                _description("垂直拖动音量表盘\n向上拖动增加音量,向下拖动减少音量。"),
                const SizedBox(height: 20),
                Stack(
                  alignment: Alignment.center,
                  children: [
                    SizedBox(
                      height: 160,
                      width: 160,
                      child: CircularProgressIndicator(
                        value: volume / 100,
                        strokeWidth: 10,
                        valueColor: const AlwaysStoppedAnimation(Color.fromARGB(210, 172, 161, 4)),
                      ),
                    ),
                    DraggableResizer(
                      axis: Axis.vertical,
                      widgetWhenDragging: _musicDialar(),
                      draggableWidget: _musicDialar(),
                      onValueChange: ((vol) {
                        setState(() {
                          volume = vol;
                          debugPrint("尺寸已更改为: $vol");
                        });
                      }),
                    ),
                  ],
                ),
                _divider(),
                const SizedBox(height: 20),

                // EXAMPLE 2: FACE RATING
                _heading("示例 2"),
                _description("水平拖动评分表情符号\n左右拖动进行评分。"),
                const SizedBox(height: 10),
                DraggableResizer(
                  shouldDraggableWidgetRotate: false,
                  shouldDraggingWidgetRotate: false,
                  showFeedback: false,
                  axis: Axis.horizontal,
                  direction: Direction.leftToRight,
                  widgetWhenDragging: _emoji(),
                  draggableWidget: _emoji(),
                  onValueChange: ((rating) {
                    setState(() {
                      if (rating >= 0 && rating < 20) {
                        ratingImg = "assets/rating/emoji1.png";
                      }
                      if (rating >= 20 && rating < 40) {
                        ratingImg = "assets/rating/emoji2.png";
                      }
                      if (rating >= 40 && rating < 60) {
                        ratingImg = "assets/rating/emoji3.png";
                      }
                      if (rating >= 60 && rating < 80) {
                        ratingImg = "assets/rating/emoji4.png";
                      }
                      if (rating >= 80 && rating < 100) {
                        ratingImg = "assets/rating/emoji5.png";
                      }
                      setState(() => ratingVal = rating);
                      debugPrint("评分已更改为: $rating");
                    });
                  }),
                ),
                _heading("${(ratingVal / 20).ceilToDouble()} / 5.0"),
                _divider(),
                const SizedBox(height: 20),

                // EXAMPLE 3: BASIC
                _heading("示例 3"),
                _description("水平拖动我\n以增加或减小我的大小"),
                const SizedBox(height: 10),
                Container(
                    height: 130,
                    width: 130,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                        color: Colors.amber, shape: BoxShape.circle),
                    child: DraggableResizer(
                      onValueChange: ((val) => setState(() {
                            speakerVal = val;
                          })),
                      axis: Axis.horizontal,
                      showFeedback: true,
                      shouldDraggingWidgetRotate: false,
                      shouldDraggableWidgetRotate: false,
                      widgetWhenDragging: _speaker(),
                      draggableWidget: _speaker(),
                    )),
                _divider(),
              ],
            )),
          ),
        ),
      ),
    );
  }

  _heading(String heading) => Text(heading,
      textAlign: TextAlign.center,
      style: const TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 16,
          color: Color.fromARGB(255, 166, 162, 162)));
  _description(String heading) => Text(heading,
      textAlign: TextAlign.center,
      style: const TextStyle(color: Color.fromARGB(255, 145, 142, 142)));
  _divider() => Container(
      margin: const EdgeInsets.all(16.0), height: 0.2, color: Colors.grey);
  _musicDialar() => Container(
      height: 150,
      width: 150,
      decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(
              color: const Color.fromARGB(233, 185, 195, 9), width: 5)),
      child: Image.asset("assets/audio_speakers.png"));
  _emoji() => Container(
        height: 120,
        width: 120,
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(ratingImg), fit: BoxFit.fitHeight),
            shape: BoxShape.circle),
      );
  _speaker() => Container(
        height: speakerVal + 60,
        width: speakerVal + 60,
        decoration: const BoxDecoration(
            image: DecorationImage(image: AssetImage("assets/nozzle.png")),
            shape: BoxShape.circle),
      );
}

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

1 回复

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


当然,以下是如何在Flutter中使用draggable_resizer插件来实现拖拽调整大小功能的代码示例。draggable_resizer是一个流行的Flutter插件,允许你创建可拖拽和调整大小的Widget。

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

dependencies:
  flutter:
    sdk: flutter
  draggable_resizer: ^x.y.z  # 请将x.y.z替换为最新版本号

然后运行flutter pub get来安装依赖。

以下是一个完整的Flutter应用示例,展示了如何使用draggable_resizer

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

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

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Draggable Resizer Demo'),
      ),
      body: Center(
        child: DraggableResizer(
          // 定义要拖拽和调整大小的子Widget
          child: Container(
            color: Colors.amber,
            child: Center(
              child: Text('Drag me and resize me!'),
            ),
          ),
          // 初始尺寸和位置
          minSize: Size(100, 100),
          maxSize: Size(500, 500),
          initialSize: Size(200, 200),
          initialPosition: Offset(100, 100),
          // 拖拽和调整大小的回调
          onDragged: (details) {
            print('Dragged to: ${details.globalPosition}');
          },
          onResized: (size) {
            print('Resized to: $size');
          },
          // 拖拽和调整大小时的背景颜色
          handleColor: Colors.blue,
          // 拖拽和调整大小时的边框颜色
          borderColor: Colors.red,
          // 边框宽度
          borderWidth: 4.0,
          // 是否显示调整大小的句柄
          isResizable: true,
          // 是否允许拖拽
          isDraggable: true,
          // 拖拽和调整大小时的阴影
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.5),
              spreadRadius: 5,
              blurRadius: 7,
              offset: Offset(0, 3), // changes position of shadow
            ),
          ],
          // 拖拽和调整大小时的反馈
          feedback: Transform.scale(
            scale: 1.1,
            child: Container(
              color: Colors.grey.withOpacity(0.5),
            ),
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,包含一个DraggableResizer Widget。DraggableResizer接受一个子Widget(在这个例子中是一个带有文本的Container),并允许用户通过拖拽和调整大小来操作它。

你可以根据需要调整minSizemaxSizeinitialSizeinitialPosition等参数来设置初始尺寸和位置。此外,你还可以通过onDraggedonResized回调来处理拖拽和调整大小的事件。

希望这个示例能帮你快速上手draggable_resizer插件的使用!

回到顶部