如何同时使用AnimatedSwitcher和CustomScrollView?

10

我想在CustomScrollView中使用动画切换状态,但它引发了错误。

class SliverAnimatedSwitcher extends StatefulWidget {
  final state;

  const SliverAnimatedSwitcher({Key key, this.state}) : super(key: key);

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

class _SliverAnimatedSwitcherState extends State<SliverAnimatedSwitcher> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            title: Text('SliverAnimatedSwitcher'),
          ),
          _buildContent(),
        ],
      ),
    );
  }

  get state => widget.state;

  Widget _buildContent() {
    var content;
    if (state.isNotEmpty == true) {
      content = SliverList(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            var item = state.items[index];
            return ListTile(
              title: Text(item.title),
            );
          },
          childCount: state.items.length,
        ),
      );
    } else if (state.isError) {
      content = SliverFillRemaining(
        key: Key('error'),
        child: Container(alignment: Alignment.center, child: Text('Error')),
      );
    } else if (state.isLoading) {
      content = SliverFillRemaining(
        key: Key('loading'),
        child: Container(alignment: Alignment.center, child: Text('Loading')),
      );
    } else {
      content = SliverFillRemaining(
        key: Key('empty'),
        child: Container(alignment: Alignment.center, child: Text('Empty')),
      );
    }
    return AnimatedSwitcher(
      duration: Duration(milliseconds: 300),
      child: content,
    );
  }
}
2个回答

6

在pub.dev上有一个名为sliver_tools的包,其中包含一个SliverAnimatedSwitcher。您可以像这样使用它:

SliverAnimatedSwitcher(
  duration: kThemeAnimationDuration,
  child: content,
)

最好的情况是,如果有一个完整的示例来说明如何使用它。 - undefined

1
由于银色小部件与在AnimatedSwitcher中作为布局构建器使用的Stack不兼容,所以会出现这种情况。
我找到了一个临时解决方案。虽然结果不等同于原始结果(只显示结果中的最后一个小部件),但我认为现在对我来说是可以接受的,因为只需要很少的努力。
  1. 首先创建一个SliverAnimatedSwitcher,其代码与AnimatedSwitcher完全相同here
  2. 修改Stack部分,仅返回currentChild(defaultLayoutBuilder)
  3. FadeTransition更改为SliverFadeTransition(defaultTransitionBuilder)

.

static Widget defaultLayoutBuilder(Widget currentChild, List<Widget> previousChildren) {
  return currentChild;
}

.

static Widget defaultTransitionBuilder(Widget child, Animation<double> animation) {
  return SliverFadeTransition(
    opacity: animation,
    sliver: child,
  );
}

如果有人能找到一种将Sliver小部件堆叠在彼此上方的方法,那么结果可能会更加完美。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接