Flutter中封装为类后CustomAnimation组件不生效问题排查
问题原因及修复方案
- 核心问题:你没有将
SidebarAnimation接收的child参数传递给内部的CustomAnimation组件CustomAnimation的builder回调中拿到的child参数,本质是你提前传给CustomAnimation自身child属性的Widget。你没有给CustomAnimation配置这个属性,导致builder拿到的child为空,自然渲染不出任何内容,动画也不会针对空组件生效。 - 次要优化点:你定义的
InfiniteNoteController参数如果在SidebarAnimation中没有实际使用,可以直接移除,避免多余的参数传递。
修复后的完整代码如下:
/// sidebar animator for showing / hiding a sidebar class SidebarAnimation extends StatelessWidget { final bool shouldShow; final Widget child; const SidebarAnimation( {Key? key, required this.shouldShow, required this.child}) : super(key: key); @override Widget build(BuildContext context) { return CustomAnimation<double>( tween: Tween<double>(begin: 0, end: 60), duration: const Duration(milliseconds: 225), curve: Curves.easeInOut, control: shouldShow ? CustomAnimationControl.play : CustomAnimationControl.playReverse, // 新增这行,将外部传入的子组件透传给CustomAnimation child: child, builder: (context, child, value) { return Transform.translate( offset: Offset(value, 0), child: child, ); }); } }
修复后直接使用SidebarAnimation传入shouldShow和子组件即可正常触发动画和渲染内容。
内容的提问来源于stack exchange,提问作者Emmanuel
相关产品推荐
相关产品推荐

