我在 Flutter 中有一个 StatefulWidget,它创建了一个对象的实例。如何防止 Flutter 每次状态改变时都创建一个新实例?
由于您没有在此处发布任何代码,我将假设您正在
build
方法中执行任何操作。
如果是这样,那么是的,只要状态重建,就会创建相同的对象/变量。为避免这种情况,您需要在构建方法之外进行变量创建和赋值。
class WhateverWidget extends StatefulWidget {
const WhateverWidget({ super.key });
@override
State<WhateverWidget> createState() => _WhateverWidgetState();
}
class _WhateverWidgetState extends State<WhateverWidget> {
final nameOfUser = 'bqubique';
@override
Widget build(BuildContext context) {
return Container(color: const Color(0xFFFFE306));
}
}
在此代码示例中,
nameOfUser
变量不会在状态刷新时重新创建。
请参考StatefulWidget类的官方文档
希望这是有道理的。