Flutter学习之路->给Hello World文本组件添加上小动画

70 阅读1分钟

文本位移渐变

import 'package:flutter/material.dart';
import 'dart:math' as math;

class CustomText extends StatefulWidget {
  @override
  _CustomTextState createState() => _CustomTextState();
}

class _CustomTextState extends State<CustomText>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller =
        AnimationController(duration: const Duration(seconds: 5), vsync: this);
    _animation = Tween<double>(begin: 0, end: 10).animate(_controller);
  }

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

  @override
  Widget build(BuildContext context) {
    final String text = "Hello World";
    return GestureDetector(
      onTap: () {
        _controller.reset();
        _controller.forward();
      },
      child: AnimatedBuilder(
          animation: _animation,
          builder: (BuildContext context, Widget? child) {
            double value = _animation.value;
            return Stack(
              children: [
                Text(
                  text,
                  style: TextStyle(
                    fontSize: 40,
                    color: Colors.white.withOpacity(0.2),
                  ),
                ),
                ClipRect(
                  child: OverflowBox(
                    maxWidth: double.infinity,
                    maxHeight: double.infinity,
                    child: Transform.translate(
                      offset: Offset(
                          math.sin(value) * 80, math.cos(value) * 80),
                      child: Text(
                        text,
                        style: TextStyle(
                          fontSize: 40,
                          foreground: Paint()
                            ..shader = const LinearGradient(colors: [
                              Colors.green,
                              Colors.yellow,
                              Colors.red,
                            ]).createShader(
                              const Rect.fromLTWH(0, 0, 375, 0),
                            )
                            ..style = PaintingStyle.stroke
                            ..strokeWidth = 4,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            );
          }),
    );
  }
}

class CustomTextPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Text'),
      ),
      body: Center(
        child: CustomText(),
      ),
    );
  }
}
```
```