繁体   English   中英

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

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

问题:如何从列表和 append 中检索到本地保存的新列表,以供同一个 class 中的方法使用。

我想将什么存储在 exerciseList 中并将其放入局部变量 List CustomExercises 中; 当我从 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;
  }

对于上下文,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;
  }

当我打印到控制台exerciseList[n].title时,它返回包含练习的列表,例如['exercise1','Bicep Curl', 'Pull Up', ]等。这些练习已经在父 class 中检索到,我会喜欢将它们存储在新列表中。 任何指导都会很棒,如果您认为需要更多背景信息,请告诉我。

未填充List customExercises的原因是因为customExercises.add()在有状态小部件内被调用。 要将新对象添加到列表中,您需要在添加项目时调用setState()

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

暂无
暂无

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

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