我如何在 Flutter 中实现 SwiftUI 的 StateObject 的语义

问题描述 投票:0回答:1

我在 Flutter 中有一个 StatefulWidget,它创建了一个对象的实例。如何防止 Flutter 每次状态改变时都创建一个新实例?

flutter
1个回答
0
投票

由于您没有在此处发布任何代码,我将假设您正在

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类的官方文档

希望这是有道理的。

© www.soinside.com 2019 - 2024. All rights reserved.