[英]Flutter: How to share an instance of statefull widget?
I have a "WidgetBackGround" statefullwidget that return an animated background for my app,我有一个“WidgetBackGround” statefullwidget 为我的应用程序返回动画背景,
I use it like this :我像这样使用它:
Scaffold( resizeToAvoidBottomInset: false, body: WidgetBackGround( child: Container(),),)
The problem is when I use navigator to change screen and reuse WidgetBackGround an other instance is created and the animation is not a the same state that previous screen.问题是当我使用导航器更改屏幕并重用 WidgetBackGround 时,会创建另一个实例,并且动画与前一个屏幕的状态不同。
I want to have the same animated background on all my app, is it possible to instance it one time and then just reuse it ?我想在我的所有应用程序上拥有相同的动画背景,是否可以将其实例化一次然后重复使用它?
WidgetBackGround.dart look like this: WidgetBackGround.dart 看起来像这样:
final Widget child;
WidgetBackGround({this.child = const SizedBox.expand()});
@override
_WidgetBackGroundState createState() => _WidgetBackGroundState();
}
class _WidgetBackGroundState extends State<WidgetBackGround> {
double iter = 0.0;
@override
void initState() {
Future.delayed(Duration(seconds: 1)).then((value) async {
for (int i = 0; i < 2000000; i++) {
setState(() {
iter = iter + 0.000001;
});
await Future.delayed(Duration(milliseconds: 50));
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return CustomPaint(painter: SpaceBackGround(iter), child: widget.child);
}
}
this is not a solution, but maybe a valid workaround:这不是解决方案,但可能是有效的解决方法:
try making the iter
a static variable, this of course won't preserve the state of WidgetBackGround
but will let the animation continue from its last value in the previous screen尝试使iter
成为静态变量,这当然不会保留WidgetBackGround
的状态,但会让动画从上一屏幕中的最后一个值继续
A valid solution (not sure if it's the best out there):一个有效的解决方案(不确定它是否是最好的):
is to use some dependency injection tool (for example get_it ) and provide your WidgetBackGround
object as a singleton for every scaffold in your app是使用一些依赖注入工具(例如get_it )并为您的应用程序中的每个脚手架提供您的WidgetBackGround
对象作为单例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.