Flutter开关动画插件flutter_switch_clipper的使用

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

Flutter开关动画插件flutter_switch_clipper的使用

flutter_switch_clipper 是一个用于Flutter应用中的动画切换插件,它通过剪切器(Clipper)实现两个小部件之间的平滑切换。本文将介绍如何使用这个插件,并提供完整的示例代码。

体验一下

您可以通过访问以下链接来查看 flutter_switch_clipper 的演示效果:

使用方法

安装插件

首先,在您的 pubspec.yaml 文件中添加依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_switch_clipper: ^最新版本号

然后运行 flutter pub get 来安装插件。

示例代码

以下是使用 flutter_switch_clipper 的完整示例代码:

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

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blueGrey[200],
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(40),
          children: <Widget>[
            // 使用FillClipper并自定义相关参数
            SwitchClipper(
              initSelect: true,
              child: const Icon(Icons.favorite, size: 200, color: Colors.redAccent),
              background: const Icon(Icons.favorite, size: 200, color: Colors.white),
              duration: const Duration(milliseconds: 800),
              customClipperBuilder: (Animation<double> animation) => FillClipper(
                animation: animation,
                fillAlignment: Alignment.center,
                fillOffset: 50,
              ),
            ),

            // 默认FillClipper
            const SwitchClipper(
              enableWhenAnimating: false,
              child: Text(
                'FlutterCandies',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 50,
                  color: Colors.amber,
                  height: 2,
                ),
              ),
              background: Text(
                'FlutterCandies',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 50,
                  color: Colors.white,
                  height: 2,
                ),
              ),
              curve: Curves.slowMiddle,
              reverseCurve: Curves.linear,
            ),

            Wrap(
              children: <Widget>[
                // 使用ShutterClipper
                SwitchClipper(
                  child: ColoredBox(
                    color: Colors.blueGrey[200] ?? Colors.blueGrey,
                    child: const Icon(Icons.accessibility_new_rounded, size: 200, color: Colors.white),
                  ),
                  background: const Icon(Icons.accessible_forward_outlined, size: 200, color: Colors.white),
                  curve: Curves.ease,
                  duration: const Duration(milliseconds: 800),
                  customClipperBuilder: (Animation<double> animation) => ShutterClipper(
                    animation: animation,
                    activeAlignment: Alignment.center,
                  ),
                ),

                // 使用CircleClipper切换图标颜色
                SwitchClipper(
                  child: const Icon(Icons.accessibility_new_rounded, size: 200, color: Colors.blueAccent),
                  background: const Icon(Icons.accessibility_new_rounded, size: 200, color: Colors.white),
                  curve: Curves.ease,
                  duration: const Duration(milliseconds: 800),
                  customClipperBuilder: (Animation<double> animation) => CircleClipper(
                    animation: animation,
                  ),
                ),

                // 使用WaveClipper切换图标颜色
                SwitchClipper(
                  child: const Icon(Icons.access_time_filled_rounded, size: 200, color: Colors.blue),
                  background: const Icon(Icons.access_time_filled_rounded, size: 200, color: Colors.white),
                  curve: Curves.ease,
                  duration: const Duration(milliseconds: 2000),
                  customClipperBuilder: (Animation<double> animation) => WaveClipper(
                    animation: animation,
                    waveAlignment: Alignment.center,
                  ),
                ),

                // 使用CameraClipper切换图标颜色
                SwitchClipper(
                  child: Container(
                    width: 200,
                    height: 200,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.blue,
                    ),
                    child: const Text(
                      'Camera',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 40,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  background: Container(
                    width: 200,
                    height: 200,
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                    ),
                  ),
                  duration: const Duration(milliseconds: 1500),
                  customClipperBuilder: (Animation<double> animation) => CameraClipper(
                    animation: animation,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 40),

            const Text('点击上方图标或文本预览效果'),
          ],
        ),
      ),
    );
  }
}

解释

  1. FillClipper:允许您自定义填充对齐和偏移量。
  2. 默认FillClipper:使用默认的填充效果。
  3. ShutterClipper:实现类似于快门的动画效果。
  4. CircleClipper:实现圆形切换效果。
  5. WaveClipper:实现波浪形切换效果。
  6. CameraClipper:实现类似相机快门的切换效果。

您可以根据需要选择不同的剪切器(Clipper),并通过调整参数来定制动画效果。希望这些示例能帮助您快速上手 flutter_switch_clipper 插件!


更多关于Flutter开关动画插件flutter_switch_clipper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter开关动画插件flutter_switch_clipper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 flutter_switch_clipper 插件来实现开关动画的示例代码。这个插件可以让你自定义开关(Switch)组件的动画效果。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_switch_clipper 依赖:

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

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

接下来,在你的 Dart 文件中,你可以按照以下步骤使用 FlutterSwitchClipper 来创建自定义开关动画:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  bool isSwitchOn = false;

  void _toggleSwitch(bool value) {
    setState(() {
      isSwitchOn = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Switch Clipper Demo'),
      ),
      body: Center(
        child: CustomSwitch(
          value: isSwitchOn,
          onChanged: _toggleSwitch,
          activeColor: Colors.green,
          inactiveColor: Colors.grey,
          activeThumbColor: Colors.white,
          inactiveThumbColor: Colors.white,
          switchClipper: const MySwitchClipper(),
        ),
      ),
    );
  }
}

class MySwitchClipper extends CustomSwitchClipper {
  const MySwitchClipper();

  @override
  Widget buildTrack(BuildContext context, double width, double height, bool isActive) {
    return AnimatedContainer(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: isActive ? Colors.greenAccent : Colors.grey[300],
        borderRadius: BorderRadius.circular(12),
      ),
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  @override
  Widget buildThumb(BuildContext context, double size, bool isActive) {
    return AnimatedContainer(
      width: size,
      height: size,
      decoration: BoxDecoration(
        color: isActive ? Colors.white : Colors.grey[900],
        borderRadius: BorderRadius.circular(size / 2),
        boxShadow: [
          BoxShadow(
            color: isActive ? Colors.green.withOpacity(0.3) : Colors.grey.withOpacity(0.3),
            spreadRadius: 2,
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }
}

class CustomSwitch extends StatelessWidget {
  const CustomSwitch({
    Key? key,
    required this.value,
    required this.onChanged,
    this.activeColor,
    this.inactiveColor,
    this.activeThumbColor,
    this.inactiveThumbColor,
    required this.switchClipper,
  }) : super(key: key);

  final bool value;
  final ValueChanged<bool> onChanged;
  final Color? activeColor;
  final Color? inactiveColor;
  final Color? activeThumbColor;
  final Color? inactiveThumbColor;
  final CustomSwitchClipper switchClipper;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => onChanged(!value),
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          switchClipper.buildTrack(
            context,
            MediaQuery.of(context).size.width * 0.4, // Adjust width as needed
            30.0, // Track height
            value,
          ),
          Positioned(
            left: value
                ? (MediaQuery.of(context).size.width * 0.4 - 30.0) / 2
                : -15.0, // Thumb position based on switch state
            child: switchClipper.buildThumb(context, 30.0, value),
          ),
        ],
      ),
    );
  }
}

在这个示例中,我们创建了一个自定义的 MySwitchClipper 类,它继承自 CustomSwitchClipper 并实现了 buildTrackbuildThumb 方法。这两个方法分别用于构建开关的轨道(track)和拇指(thumb)。

CustomSwitch 组件封装了开关的逻辑和外观,并使用 GestureDetector 来处理点击事件。在 Stack 中,我们堆叠了轨道和拇指,拇指的位置根据开关的状态动态调整。

你可以根据需要进一步自定义 MySwitchClipper 中的动画效果,比如改变颜色、添加更多的阴影效果或调整动画曲线等。

回到顶部