简体   繁体   English

有效更新 SetState() 中的一系列变量(Dart-Flutter)

[英]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.您可以使用classmap来处理您的数据。

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 a factory that return the same type of currentData . Obs: copyWith是一个返回相同类型currentDatafactory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Dart-Flutter 中的异步 Function 错误 - Asynchronous Function Error In Dart-Flutter 在 dart-flutter 中将字符串拆分为字母 - split a String into letters in dart-flutter 在 dart-flutter 中将字符串拆分为列列表 - split a String into colums list in dart-flutter 我如何在 dart-flutter 上获得代码安全性 - How can i get code safety on dart-flutter RxDart 的 dart-flutter 中的 Concanete 2 firestore QuerySnapShot 流 - Concanete 2 firestore QuerySnapShot streams in dart-flutter by RxDart Flutter/Dart:在使用 setState() 时更新一些变量而不是其他变量 - Flutter/Dart: update some variables but not others when using setState() 如何在 dart-flutter 中对这样的时间列表进行排序 [ 2:00 AM , 10:00 AM , 6:00 PM ]? - How to sort a list of timings like this [ 2:00 AM , 10:00 AM , 6:00 PM ] in dart-flutter? 如何使用 dart-flutter 每天重复本地通知? 以及如何将“2:00 AM”时间格式解析为 TimeZone? - How to repeat local notification every day with dart-flutter? and how to parse '2:00 AM' time format To TimeZone? 我需要帮助进行从 Dart-Flutter 到 FireBase 的复合查询 - I need help making a compound query from Dart-Flutter to FireBase Dart - Flutter:setState() 功能错误 - Dart - Flutter : setState() functionality error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM