首页 > 解决方案 > 在未知大小的小部件上动画扩展/收缩

问题描述

我们想要显示从数据库中获取的图像和文本列表。当您点击其中一个图像/文本时,它们应该以动画形式展开。使用当前代码,扩展动画按预期工作,但反之则不行。图像在没有动画的情况下缩小,然后是AnimatedSize动画。请参阅:Flutter AnimatedSize 仅在一个方向上起作用

由于我们没有纯色,因此该问题的解决方案并不适合我们。

它确实适用于具有以下代码的图像,但它并不理想,并且文本根本不起作用。

Container(
  foregroundDecoration: BoxDecoration(
    image: DecorationImage(
      image: CachedNetworkImageProvider(
        snapshot.data.documents[index]['image'],
      ),
      fit: BoxFit.cover,
      alignment: Alignment.topCenter,
    ),
  ),
  child: AnimatedSize(
    duration: Duration(milliseconds: 300),
    vsync: this,
    child: Opacity(
      opacity: 0,
      child: Container(
        height: _expandedIndex == index ? null : 250,
        child: CachedNetworkImage(
          imageUrl: snapshot.data.documents[index]['image'] ?? '',
          fit: BoxFit.cover,
          width: double.infinity,
        ),
      ),
    ),
  ),
),

我发现很多其他人有同样的问题,但我从来没有找到有效的解决方案,所以非常欢迎任何帮助。

谢谢!

标签: flutteranimation

解决方案


尝试了sizeTransition小部件,它对我有用。AnimationController并且Tween没有必要。这是我的工作代码。

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

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

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget>
    with TickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    duration: const Duration(seconds: 1),
    vsync: this,
  );
  late final Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.fastOutSlowIn,
  );

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextButton(
            child: const Text('toggle'),
            onPressed: () => _controller.isDismissed
                ? _controller.forward()
                : _controller.reverse(),
          ),
          SizeTransition(
            sizeFactor: _animation,
            axis: Axis.vertical,
            axisAlignment: -1,
            child: Container(
              color: Colors.amberAccent,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: const [Text("Hello"), Text("World")],
              ),
            ),
          ),
        ],
      ),
    );
  }
}


推荐阅读