gpt4 book ai didi

flutter - 如何防止对象在每次调用时被重新初始化? - Dart/flutter

转载 作者:行者123 更新时间:2023-12-03 04:20:38 25 4
gpt4 key购买 nike

对于以下代码段:
//主类的代码段


class MainState extends State<Main>{

MusicMaterial musicObj = MusicMaterial();
SoundsMaterial soundObj = SoundsMaterial();

@override
Widget build(BuildContext context) {
return Container(
child: something.value == 0
? musicObj
: soundObj
);
}
}

// MusicMaterial类的摘要

class MusicMaterialState extends State<MusicMaterial>{
@override
Widget build(BuildContext context) {
return Row(
AnotherClass obj1 = AnotherClass(0, 'test'),
AnotherClass obj2 = AnotherClass(1, 'test'),
);
}
}

// AnotherClass类的代码段

class AnotherClassState extends State<AnotherClass>{
import '../globals.dart' as globals;

@override
void initState() {
globals.globalCounter++; // this variable is just a global variable from the globals.dart page
}

}

// global.dart的代码段
library my_prj.globals;

globalCounter = 0;

每当Main State类中的“if”状态更新时,它都会继续创建一个新实例。因此,例如,全局计数器的值一直从0上升到2到4 ... 8 ...我们如何确保对象不会每次都重新初始化,例如void initState()从AnotherClassState仅被调用一次?即该值保持为2并且仅为2。
我试过使用“AutomaticKeepAliveClientMixin和@override bool get wantKeepAlive => true”-即保持它处于 Activity 状态,因此当下次调用它时,它不会再次调用initState(),但是它不起作用。

最佳答案

希望我能正确理解您的需求。似乎您希望每个类类型的计数器仅增加一次。我敢肯定有不同的方法可以做到,但是我想让globalCounter变得更加复杂

class GlobalCounter {
List<String> _keys = List<String>();
int _counter = 0;

int get counter => _counter;

void increaseCounter(String key) {
// increase only if the key passed as parameter didn't increase already
if (!_keys.contains(key)) {
_counter++;
_keys.add(key);
}
}
}

globalCounter = GlobalCounter();
然后你可以像这样使用它
@override
void initState() {
// pass the type of the instance trying to increase the counter
globals.globalCounter.increaseCounter(this.runtimeType.toString());
}

关于flutter - 如何防止对象在每次调用时被重新初始化? - Dart/flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62844557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com