[英]Update a series of variable in SetState() efficiently (Dart-Flutter)
I can't find a simple way to update a series of variables in my Flutter project.我在我的 Flutter 项目中找不到更新一系列变量的简单方法。 I first tried using Enums and functions to change the variables inside a setState((){})
call.我首先尝试使用枚举和函数来更改setState((){})
调用中的变量。 I have something like this:我有这样的事情:
void changeMode(Mode mode) {
if (mode == Mode.start) {
print('App is now in start mode');
mode = Mode.start;
bool1 = true;
bool2 = false;
bool3 = false;
color1 = kAColor1;
color2 = kAColor2;
} else if ...}
But nothing gets updated, I imagine it's due the fact that my function doesn't return anything.但是没有任何更新,我想这是因为我的 function 没有返回任何内容。
If I hard code every single variable in setState((){})
it works fine, but it's absolutely inefficient and a mess to correct.如果我对setState((){})
中的每个变量进行硬编码,它可以正常工作,但它绝对是低效的并且需要纠正。
Maybe I should go with classes?也许我应该 go 上课? Would I need to create a superclass containing all the subclasses to do something like this?我需要创建一个包含所有子类的超类来做这样的事情吗?
Every time that you call setState you UI will rebuild.每次调用 setState 时,UI 都会重建。 You can use class
or map
to manipulate your data.您可以使用class
或map
来处理您的数据。
With class:使用 class:
setState(() {
currentData = actualData.copyWith(bool1: false)
})
This way, you change only data that is different from currentData
.这样,您只更改与currentData
不同的数据。 On this example, I maintain all information from currentData
and change only bool1
value.在这个例子中,我维护了currentData
的所有信息并且只改变了bool1
值。
Obs:
copyWith
is afactory
that return the same type ofcurrentData
. Obs:copyWith
是一个返回相同类型currentData
的factory
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.