Flutter 3D动画效果插件flutter_3d_ball的使用

Flutter 3D动画效果插件flutter_3d_ball的使用

简介

flutter_3d_ball 是一个用于实现自动旋转的仿3D球体的Flutter插件。它可以用来创建具有动态效果的用户界面元素。

3D球体示例

特性

  • 支持手动/自动转动
  • 支持暂停/继续转动控制
  • 支持高亮处理部分标签

使用步骤

以下是一个完整的示例代码,展示了如何在Flutter项目中使用 flutter_3d_ball 插件。

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

import 'package:flutter/services.dart';
import 'package:flutter_3d_ball/flutter_3d_ball.dart';

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late Future<List<RBallTagData>> _recommendUserFuture;
  bool isAnimate = true;

  [@override](/user/override)
  void initState() {
    _recommendUserFuture = _getRecommendUserList();
    super.initState();
  }

  Future<List<RBallTagData>> _getRecommendUserList() async {
    await Future.delayed(Duration(milliseconds: 3000));
    List datas = [
      {"tag": "💜ℱℛ❧吃货默染🈂🈷💜", "id": "5fe618941ff65076de93c264"},
      {"tag": "席辰", "id": "5d86e5ede5dd2942ab0a1917"},
      // 其他数据...
    ];
    List<RBallTagData> list = [];
    if (datas.isNotEmpty) {
      datas.forEach((element) {
        RBallTagData tag = RBallTagData.fromJson(element);
        list.add(tag);
      });
    }
    return list;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blue,
        appBar: AppBar(
          title: const Text(
            'Plugin example app',
            style: TextStyle(color: Color(0xFF333333)),
          ),
          backgroundColor: Colors.transparent,
          shadowColor: Colors.transparent,
        ),
        body: Container(
          width: double.infinity,
          child: FutureBuilder<List<RBallTagData>>(
            future: _recommendUserFuture,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              double _wh = ((MediaQuery.of(context).size.width - 2 * 10) * 32 / 35);
              return Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.width,
                alignment: Alignment.center,
                child: snapshot.connectionState == ConnectionState.done
                    ? snapshot.hasError
                        ? Text("Error: ${snapshot.error}")
                        : RBallView(
                            isAnimate: isAnimate,
                            isShowDecoration: true,
                            mediaQueryData: MediaQuery.of(context),
                            keywords: snapshot.data,
                            highlight: [snapshot.data[0]],
                            onTapRBallTagCallback: (RBallTagData data) {
                              print('点击回调:${data.tag}');
                            },
                            textColor: Colors.white,
                            highLightTextColor: Colors.red,
                            decoration: BoxDecoration(
                              color: Colors.blue,
                              borderRadius: BorderRadius.circular((_wh / 2).toDouble()),
                              boxShadow: [
                                BoxShadow(
                                  color: Color(0xffffffff),
                                  blurRadius: 5.0,
                                )
                              ],
                            ),
                          )
                    : Text('Searching for friends...'),
              );
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          child: Center(
            child: Icon(isAnimate ? Icons.pause : Icons.play_arrow),
          ),
          onPressed: () {
            setState(() {
              isAnimate = !isAnimate;
            });
          },
        ),
      ),
    );
  }
}

代码解释

  1. 导入必要的包

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'package:flutter/services.dart';
    import 'package:flutter_3d_ball/flutter_3d_ball.dart';
    
  2. 定义主应用类 MyApp 和状态管理类 _MyAppState

    class MyApp extends StatefulWidget {
      [@override](/user/override)
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      late Future<List<RBallTagData>> _recommendUserFuture;
      bool isAnimate = true;
    
      [@override](/user/override)
      void initState() {
        _recommendUserFuture = _getRecommendUserList();
        super.initState();
      }
    
  3. 获取推荐用户列表

    Future<List<RBallTagData>> _getRecommendUserList() async {
      await Future.delayed(Duration(milliseconds: 3000));
      List datas = [
        {"tag": "💜ℱℛ❧吃货默染🈂🈷💜", "id": "5fe618941ff65076de93c264"},
        {"tag": "席辰", "id": "5d86e5ede5dd2942ab0a1917"},
        // 其他数据...
      ];
      List<RBallTagData> list = [];
      if (datas.isNotEmpty) {
        datas.forEach((element) {
          RBallTagData tag = RBallTagData.fromJson(element);
          list.add(tag);
        });
      }
      return list;
    }
    
  4. 构建UI

    [@override](/user/override)
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          backgroundColor: Colors.blue,
          appBar: AppBar(
            title: const Text(
              'Plugin example app',
              style: TextStyle(color: Color(0xFF333333)),
            ),
            backgroundColor: Colors.transparent,
            shadowColor: Colors.transparent,
          ),
          body: Container(
            width: double.infinity,
            child: FutureBuilder<List<RBallTagData>>(
              future: _recommendUserFuture,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                double _wh = ((MediaQuery.of(context).size.width - 2 * 10) * 32 / 35);
                return Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.width,
                  alignment: Alignment.center,
                  child: snapshot.connectionState == ConnectionState.done
                      ? snapshot.hasError
                          ? Text("Error: ${snapshot.error}")
                          : RBallView(
                              isAnimate: isAnimate,
                              isShowDecoration: true,
                              mediaQueryData: MediaQuery.of(context),
                              keywords: snapshot.data,
                              highlight: [snapshot.data[0]],
                              onTapRBallTagCallback: (RBallTagData data) {
                                print('点击回调:${data.tag}');
                              },
                              textColor: Colors.white,
                              highLightTextColor: Colors.red,
                              decoration: BoxDecoration(
                                color: Colors.blue,
                                borderRadius: BorderRadius.circular((_wh / 2).toDouble()),
                                boxShadow: [
                                  BoxShadow(
                                    color: Color(0xffffffff),
                                    blurRadius: 5.0,
                                  )
                                ],
                              ),
                            )
                      : Text('Searching for friends...'),
                );
              },
            ),
          ),
          floatingActionButton: FloatingActionButton(
            child: Center(
              child: Icon(isAnimate ? Icons.pause : Icons.play_arrow),
            ),
            onPressed: () {
              setState(() {
                isAnimate = !isAnimate;
              });
            },
          ),
        ),
      );
    }
    

更多关于Flutter 3D动画效果插件flutter_3d_ball的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,关于Flutter中的flutter_3d_ball插件的使用,下面是一个简单的代码案例,展示如何使用该插件来创建3D动画效果。flutter_3d_ball插件允许你在Flutter应用中实现3D球体动画效果。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_3d_ball: ^0.1.1  # 请注意版本号,这里使用的是假设的版本号,请根据实际情况调整

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

接下来,在你的Dart文件中,你可以使用flutter_3d_ball提供的组件和动画来创建3D效果。以下是一个简单的示例代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter 3D Ball Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter 3D Ball Demo'),
        ),
        body: Center(
          child: ThreeDBallAnimation(),
        ),
      ),
    );
  }
}

class ThreeDBallAnimation extends StatefulWidget {
  @override
  _ThreeDBallAnimationState createState() => _ThreeDBallAnimationState();
}

class _ThreeDBallAnimationState extends State<ThreeDBallAnimation> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 5),
      vsync: this,
    )..repeat(reverse: true);

    _animation = Tween<double>(begin: 0, end: 2 * 3.141592653589793).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.linear,
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      child: Container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.transparent,
        ),
        child: Center(
          child: Text(
            '3D Ball',
            style: TextStyle(color: Colors.white, fontSize: 24),
          ),
        ),
      ),
      builder: (context, child) {
        return Transform.rotate(
          angle: _animation.value,
          alignment: Alignment.center,
          child: ThreeDBall(
            size: 100,
            color: Colors.blue,
            child: child,
          ),
        );
      },
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个3D球体动画。ThreeDBall组件用于显示3D球体,而AnimatedBuilderAnimationController用于控制球体的旋转动画。

  • ThreeDBall组件接受sizecolor参数来设置球体的大小和颜色。
  • AnimatedBuilder监听动画值的变化,并应用Transform.rotate来旋转球体。
  • AnimationController控制动画的时长和循环方式。

请注意,flutter_3d_ball插件的具体API可能会有所不同,因此请参考其官方文档和示例代码以获取最新和最准确的信息。此外,由于插件可能不断更新,上面的代码示例可能需要根据实际插件版本进行调整。

回到顶部