首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何防止丢弃StatefulWidget?

如何防止丢弃StatefulWidget?
EN

Stack Overflow用户
提问于 2020-11-14 12:30:00
回答 1查看 313关注 0票数 1

在树构建逻辑中添加条件构造会导致挂载/卸载小部件。如果小部件内部带有控制器,这反过来又会导致恼人的动画问题。

您如何告诉Flutter阻止widget状态被释放,而是在树的另一部分中搜索它?

代码语言:javascript
复制
build(BuildContext context) {
  var value = controller.value;

  /// Let's avoid blinking at high opacity, save CPU at the same time

  /// commenting this line will result in smooth animation
  /// when it is uncommented, Flutter will dispose the State which was previously lying under Opacity() widget  
  if(value >= 0.95) return MyAnimatedWidget();

  return Opacity(
   opacity: value,
   child: MyAnimatedWidget();
  );
}
EN

回答 1

Stack Overflow用户

发布于 2020-11-14 14:01:39

当您在代码中编写MyAnimatedWidget()时,这意味着您将再次启动一个新的窗口小部件实例,这就是为什么旧的窗口小部件被释放,因为它不再被使用。

您可以在类中创建一个MyAnimatedWidget()类型的字段,并将其与不透明或不透明一起返回。所以我将只是你的小部件的一个实例,我不会被处理掉。

代码语言:javascript
复制
MyAnimatedWidget animatedWidget = MyAnimatedWidget();

build(BuildContext context) {
  var value = controller.value;

  /// Let's avoid blinking at high opacity, save CPU at the same time

  /// commenting this line will result in smooth animation
  /// when it is uncommented, Flutter will dispose the State which was previously lying under Opacity() widget  
  if(value >= 0.95) return animatedWidget ;

  return Opacity(
   opacity: value,
   child: animatedWidget ;
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64830948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档