📜  如何使 appbar 的标题居中颤动 (1)

📅  最后修改于: 2023-12-03 14:51:49.208000             🧑  作者: Mango

如何使 AppBar 的标题居中颤动

在 Flutter 中,我们可以使用自定义的动画来实现 AppBar 标题的居中颤动效果。下面是一个简单的介绍和代码示例。

概述

要实现 AppBar 标题的居中颤动效果,我们可以结合使用 AnimatedBuilderTweenAnimatedBuilder 是一个可以构建动画的小部件,而 Tween 则是一个可以定义动画的路径和值的类。

在这个示例中,我们将使用 TransformRotation 来实现标题的居中颤动效果。

示例代码
import 'package:flutter/material.dart';

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

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

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

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController _animationController;
  Animation<double> _animation;

  @override
  void initState() {
    super.initState();

    _animationController =
        AnimationController(duration: Duration(seconds: 1), vsync: this)
          ..repeat(reverse: true);

    _animation = Tween(begin: -0.05, end: 0.05).animate(_animationController);
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: AnimatedBuilder(
          animation: _animation,
          builder: (BuildContext context, Widget child) {
            return Transform.rotate(
              angle: _animation.value,
              child: child,
            );
          },
          child: Text(
            'My AppBar Title',
            style: TextStyle(fontSize: 20.0),
          ),
        ),
        centerTitle: true,
      ),
      body: Center(
        child: Text(
          'Hello Flutter!',
          style: TextStyle(fontSize: 24.0),
        ),
      ),
    );
  }
}
解析

_MyHomePageState 类中,我们创建了一个 AnimationController 和一个 AnimationAnimationController 控制动画的持续时间,并在结束时自动反转动画。Animation 描述了动画的路径和值范围。

build 方法中,我们将 AppBar 的标题包装在一个 AnimatedBuilder 中。AnimatedBuilder 通过监听动画的变化来重建小部件树,并将变化的值传递给 builder 方法。

builder 方法中,我们将标题小部件用 Transform.rotate 包裹起来,根据动画的值设置旋转角度。当动画播放时,标题会以微小的旋转角度居中颤动。

最后,我们在 AppBar 中设置属性 centerTitle: true 来确保标题居中显示。

结论

通过以上代码,我们可以实现 AppBar 标题的居中颤动效果。你也可以根据自己的需求调整动画的效果和持续时间。希望这个介绍对你有帮助!