Flutter滑动交互插件swipeable_tile的使用

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

Flutter滑动交互插件swipeable_tile的使用

插件介绍

swipeable_tile 是一个Flutter插件,用于创建可滑动的交互式卡片。与内置的 Dismissible 组件相比,swipeable_tile 提供了更丰富的动画效果和更好的用户体验,特别是在实现类似Gmail、Telegram等应用中的滑动操作时。

主要特性

  • 动画效果:滑动时会有平滑的动画效果,包括圆角和阴影。
  • 背景动画:可以在滑动过程中动态构建并动画化背景。
  • 触发动作:支持滑动到一定距离后触发特定动作,如回复消息。
  • 多种构造函数:提供了四种不同的构造函数来满足不同场景的需求。

安装与导入

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

dependencies:
  swipeable_tile: ^latest_version # 替换为最新版本号

然后运行 flutter pub get 来安装包。接下来,在Dart文件顶部导入此包:

import 'package:swipeable_tile/swipeable_tile.dart';

使用示例

以下是一个完整的示例代码,展示了如何在应用程序中使用 swipeable_tile 插件。该例子包含三个页面:普通用法、卡片样式以及聊天回复功能。

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:swipeable_tile/swipeable_tile.dart';
import 'package:vibration/vibration.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryTextTheme: TextTheme(headline6: TextStyle(color: Colors.grey[800])),
        appBarTheme: const AppBarTheme(color: Colors.white, elevation: 0.0),
        primarySwatch: Colors.blue,
        canvasColor: Colors.white54,
      ),
      home: const MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return PageView(
      physics: const ClampingScrollPhysics(),
      children: const <Widget>[
        NormalScreen(),
        CardScreen(),
        ChatReplyScreen(),
      ],
    );
  }
}

// 普通用法页面
class NormalScreen extends StatefulWidget {
  const NormalScreen({Key? key}) : super(key: key);

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

class _NormalScreenState extends State<NormalScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(centerTitle: true, title: const Text('Nomal Usecase')),
      backgroundColor: Colors.white,
      body: ListView(
        children: persons.map((Person person) {
          return SwipeableTile(
            color: Colors.white,
            swipeThreshold: 0.2,
            direction: SwipeDirection.horizontal,
            isElevated: false,
            borderRadius: 0,
            onSwiped: (_) {},
            backgroundBuilder: (_, SwipeDirection direction, AnimationController progress) {
              if (direction == SwipeDirection.endToStart) {
                return Container(color: Colors.red);
              } else if (direction == SwipeDirection.startToEnd) {
                return Container(color: Colors.blue);
              }
              return Container();
            },
            key: UniqueKey(),
            child: ListTile(
              leading: ClipRRect(
                borderRadius: BorderRadius.circular(48),
                child: Image.network(person.imageURL),
              ),
              title: Text(person.name, style: const TextStyle(fontWeight: FontWeight.w500)),
              subtitle: Text('${person.state} ${person.streetAddress}'),
            ),
          );
        }).toList(),
      ),
    );
  }
}

// 卡片样式页面
class CardScreen extends StatefulWidget {
  const CardScreen({Key? key}) : super(key: key);

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

class _CardScreenState extends State<CardScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(centerTitle: true, title: const Text('Card Tile')),
      backgroundColor: Colors.white,
      body: ListView(
        children: persons.map((Person person) {
          return SwipeableTile.card(
            color: const Color(0xFFab9ee8),
            shadow: BoxShadow(color: Colors.black.withOpacity(0.35), blurRadius: 4, offset: Offset(2, 2)),
            horizontalPadding: 16,
            verticalPadding: 8,
            direction: SwipeDirection.horizontal,
            onSwiped: (_) {},
            backgroundBuilder: (_, SwipeDirection direction, AnimationController progress) {
              return AnimatedBuilder(
                animation: progress,
                builder: (_, __) {
                  return AnimatedContainer(
                    duration: const Duration(milliseconds: 400),
                    color: progress.value > 0.4 ? const Color(0xFFed7474) : const Color(0xFFeded98),
                  );
                },
              );
            },
            key: UniqueKey(),
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 4.0),
              child: ListTile(
                leading: ClipRRect(borderRadius: BorderRadius.circular(48), child: Image.network(person.imageURL)),
                title: Text(person.name, style: const TextStyle(fontWeight: FontWeight.w500, color: Colors.white)),
                subtitle: Text('${person.state} ${person.city}', style: const TextStyle(color: Colors.white)),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}

// 聊天回复页面
class ChatReplyScreen extends StatefulWidget {
  const ChatReplyScreen({Key? key}) : super(key: key);

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

class _ChatReplyScreenState extends State<ChatReplyScreen> {
  late TextEditingController _controller;
  final FocusNode _focusNode = FocusNode();
  Person? _selectedPerson;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(centerTitle: true, title: const Text('Swipe To Reply')),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              children: persons.map((Person person) {
                return SwipeableTile.swipeToTrigger(
                  behavior: HitTestBehavior.translucent,
                  isElevated: false,
                  color: Colors.white,
                  swipeThreshold: 0.2,
                  direction: SwipeDirection.endToStart,
                  onSwiped: (_) {
                    _focusNode.requestFocus();
                    setState(() {
                      _selectedPerson = person;
                    });
                  },
                  backgroundBuilder: (_, SwipeDirection direction, AnimationController progress) {
                    bool vibrated = false;
                    return AnimatedBuilder(
                      animation: progress,
                      builder: (_, __) {
                        if (progress.value >= 0.9999 && !vibrated) {
                          Vibration.vibrate(duration: 40);
                          vibrated = true;
                        } else if (progress.value < 0.9999) {
                          vibrated = false;
                        }
                        return Container(
                          alignment: Alignment.centerRight,
                          child: Padding(
                            padding: const EdgeInsets.only(right: 16.0),
                            child: Transform.scale(
                              scale: Tween<double>(begin: 0.0, end: 1.2).animate(CurvedAnimation(parent: progress, curve: const Interval(0.5, 1.0, curve: Curves.linear))).value,
                              child: Icon(Icons.reply, color: Colors.black.withOpacity(0.7)),
                            ),
                          ),
                        );
                      },
                    );
                  },
                  key: UniqueKey(),
                  child: MessageBubble(url: person.imageURL, message: person.message, name: person.name),
                );
              }).toList(),
            ),
          ),
          // ... 其他代码保持不变 ...
        ],
      ),
    );
  }
}

// 消息气泡组件
class MessageBubble extends StatelessWidget {
  final String name;
  final String message;
  final String url;

  const MessageBubble({Key? key, required this.message, required this.name, required this.url}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(top: 16.0, left: 16.0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(48),
            child: Image.network(url, width: 48, height: 48),
          ),
        ),
        Expanded(
          child: Container(
            padding: const EdgeInsets.all(16),
            margin: const EdgeInsets.all(16),
            decoration: BoxDecoration(color: const Color(0xFFa1ffb7), borderRadius: BorderRadius.circular(16)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(name, style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 18, color: Color(0xFF457d52))),
                const SizedBox(height: 8.0),
                Text(message),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

// 测试数据
List<Person> persons = [
  Person(
    name: 'Timothy Altenwerth',
    city: 'East Port Vincechester',
    state: 'Michigan',
    streetAddress: '565359 Fisher Stravenue',
    imageURL: 'https://raw.githubusercontent.com/watery-desert/assets/main/swipeable_tile/babies/baby1.png',
    message: 'I heard babies needs more love nowadays. Please hug and kiss me more often.',
  ),
  // 更多测试数据...
];

class Person {
  final String name;
  final String city;
  final String streetAddress;
  final String state;
  final String imageURL;
  final String message;

  Person({
    required this.name,
    required this.city,
    required this.state,
    required this.streetAddress,
    required this.imageURL,
    required this.message,
  });
}

以上代码展示了如何使用 swipeable_tile 实现基本的滑动交互,并结合振动反馈和背景动画来增强用户体验。您可以根据自己的需求调整参数或扩展功能。


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

1 回复

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


当然,下面是一个关于如何在Flutter中使用swipeable_tile插件的示例代码。swipeable_tile是一个允许用户通过滑动来进行交互的Flutter插件。

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

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

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

接下来是一个简单的示例代码,展示如何在Flutter中使用swipeable_tile

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  List<String> tiles = ['Tile 1', 'Tile 2', 'Tile 3', 'Tile 4'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Swipeable Tile Example'),
      ),
      body: ListView.builder(
        itemCount: tiles.length,
        itemBuilder: (context, index) {
          return SwipeableTile(
            onSwipeLeft: () {
              setState(() {
                // 可以在这里处理左滑逻辑,比如删除条目
                tiles.removeAt(index);
              });
            },
            onSwipeRight: () {
              setState(() {
                // 可以在这里处理右滑逻辑,比如添加条目或者标记为已读
                // 这里简单打印日志
                print('Tile ${tiles[index]} swiped right');
              });
            },
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(tiles[index]),
              ),
            ),
          );
        },
      ),
    );
  }
}

代码解释

  1. 依赖导入: 在pubspec.yaml文件中添加swipeable_tile依赖,并在代码中导入它。

  2. 构建应用: 使用MaterialApp构建应用,并设置主页为MyHomePage

  3. 构建主页: 主页使用ListView.builder来构建可滑动的列表项。每个列表项是一个SwipeableTile

  4. 处理滑动事件

    • onSwipeLeft:当用户向左滑动时,调用该回调。在这个示例中,我们删除被滑动的条目。
    • onSwipeRight:当用户向右滑动时,调用该回调。在这个示例中,我们简单打印一条日志。
  5. UI展示: 每个SwipeableTile包含一个CardCard中显示文本内容。

你可以根据需要修改这个示例,比如添加更多复杂的逻辑处理,或者自定义UI。希望这个示例对你有所帮助!

回到顶部