简体   繁体   English

Flutter/Dart:如何从方法返回一个列表并将其设置为另一个列表

[英]Flutter/Dart: How to return a List from a method and set it to another List

Problem: How to retrieve from a list and append to a new list saved locally, to be used by methods in the same class.问题:如何从列表和 append 中检索到本地保存的新列表,以供同一个 class 中的方法使用。

I would like to store whats in exerciseList and put it into the local variable List CustomExercises;我想将什么存储在 exerciseList 中并将其放入局部变量 List CustomExercises 中; When I return custom exercises from getAllExercisesAsStrings() it doesn't update.当我从 getAllExercisesAsStrings() 返回自定义练习时,它不会更新。

class GenerateCustom extends ExerciseListState {
  int rnd;

  GenerateCustom({this.difficulty});
  final int difficulty;
  String workout;
  String ex1;
  String ex2;
  String ex3;
  String ex4;
  String ex5;

  List customExercises = [];

  //get list of custom workouts
  List getAllExercisesAsStrings(customExercises) {
    var n;
    for (n = 0; n < exerciseList.length; n++) {
//      print(exerciseList[n].title);
      customExercises.add(exerciseList[n].title);
    }
    return customExercises;
  }

For context the getCustomType() gets a random exercise from the list to be displayed.对于上下文,getCustomType() 从要显示的列表中获取随机练习。

String getCustomType() {
    var random = Random();
    var i = random.nextInt(customExercises.length);
    print(customExercises[i]);
    return customExercises[i];
  }

  String cExerciseOne() {
    if (difficulty == 1) {
      workout =
          ('1: ' + getCustomType() + ' ' + getRepsEasy() + 'x' + getSetsEasy());
    } else if (difficulty == 2) {
      workout = ('1: ' +
          getCustomType() +
          ' ' +
          getRepsMedium() +
          'x' +
          getSetsMedium());
    } else {
      workout =
          ('1: ' + getCustomType() + ' ' + getRepsHard() + 'x' + getSetsHard());
    }
    return workout;
  }

When I print to console exerciseList[n].title it returns the list with the exercises eg ['exercise1','Bicep Curl', 'Pull Up', ] etc. These exercises have already been retrieved in the parent class and I would like to store them in the new list.当我打印到控制台exerciseList[n].title时,它返回包含练习的列表,例如['exercise1','Bicep Curl', 'Pull Up', ]等。这些练习已经在父 class 中检索到,我会喜欢将它们存储在新列表中。 Any guidance would be great and if you think more context is needed let me know.任何指导都会很棒,如果您认为需要更多背景信息,请告诉我。

The reason why List customExercises isn't populated is because customExercises.add() is being called inside a Stateful Widget.未填充List customExercises的原因是因为customExercises.add()在有状态小部件内被调用。 To add new Objects to the List, you'd need to call setState() when an item is added.要将新对象添加到列表中,您需要在添加项目时调用setState()

setState(() {
  customExercises.add(exerciseList[n].title);
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM