3

私はIconButton、通常、それはアイコンですIcons.expand_moreが、それを押すと、そのアイコンは になりますIcons.expand_less。これをアニメーション化して、そのボタンを押すと、回転して上から下を指すようにします。を押すと同じように、アニメーションが回転するexpand_lessはずです。expand_moreどうすればこれを達成できますか? 以下は私のコードです:

    IconButton(
      icon:  _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more),
      onPressed: () {
        setState(() {
           _expanded = !_expanded;
        });
      },
   )

私はanimatedContainerを使用しようとしましたが、2つの異なるアイコンを使用していて、これでは実現できない回転効果があるため、うまくいきませんでした。また、以下のアプローチでアイコンを回転させようとしましたが、0 度から 180 度まで回転しているときにアニメーションを表示できません。

IconButton(
              icon: AnimatedContainer(
                  duration: Duration(seconds: 3),
                  child: Transform.rotate(
                      angle: _expanded ? 0 : 180 * math.pi / 180,
                      child: Icon(Icons.expand_less))),
              // icon:
              //     _expanded ? Icon(Icons.expand_less) : Icon(Icons.expand_more),
              onPressed: () {
                setState(() {
                  _expanded = !_expanded;
                });
              },
            )

これは展開前です:

拡張前

これは展開後です:

拡張後

ボタンクリック時の回転アニメーションが欲しい。

4

3 に答える 3

0

あなたが必要とするもののために私が作ったこのテストサンプルをチェックしてください.

これは、フラッターの良い提案である曲線も適用します。

import 'package:flutter/material.dart';

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

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

class _RotateIconState extends State<RotateIcon>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        duration: const Duration(milliseconds: 500), vsync: this);
    _animation =
        Tween(begin: 0.0, end: .5).animate(CurvedAnimation(
        parent: _controller, curve: Curves.easeOut));
    }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Column(
            children: [
              RotationTransition(
                turns: _animation,
                child: const Icon(Icons.expand_more),
              ),
              ElevatedButton(
                  onPressed: () {
                    if (_controller.isDismissed) {
                      _controller.forward();
                    } else {
                      _controller.reverse();
                    }
                  },
                  child: const Text("Animate"))
            ],
          )),
    );
  }
}

于 2021-06-29T09:30:14.290 に答える