简体   繁体   中英

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.

I would like to store whats in exerciseList and put it into the local variable List CustomExercises; When I return custom exercises from getAllExercisesAsStrings() it doesn't update.

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.

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. 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. To add new Objects to the List, you'd need to call setState() when an item is added.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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