Flutter列表值被意外更新

时间:2019-08-17 21:35:37

标签: list arraylist flutter dart

在下面的代码中,“第二个Sel食物日期”的食物日期应与“初始Sel食物日期”相匹配,但它们不是因为“ tempSelected [i] .set_eatenDateTime = copyToDate.millisecondsSinceEpoch;”正在更新两个列表。如何防止foodListSelected更新?如果重要,将使用流提供程序将foodListSelected的初始值传递到类中。

List<FoodModel> tempSelected = new List();

    for (var i = 0; i < foodListSelected.length; i++) {
      tempSelected.add(foodListSelected[i]);
    }

    for (var i = 0; i < tempSelected.length; i++) {

      print('Initital Sel Food Date: ' + DateFormat('E-MM-yyyy hh:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(foodListSelected[i].eatenDateTime)));

      DateTime eatenDateTime = DateTime.fromMillisecondsSinceEpoch(tempSelected[i].eatenDateTime);
      DateTime copyToDate = DateTime(picked.year, picked.month, picked.day, eatenDateTime.hour, eatenDateTime.minute, eatenDateTime.second);

      // ISSUE!!!!!
      // This is some how setting foodListSelected[i].eatenDateTime as well.
      tempSelected[i].set_eatenDateTime = copyToDate.millisecondsSinceEpoch;


      tempSelected[i].set_selected = false;
      _createFood('eaten_food', tempSelected[i]);

    }
  }

  for (var i = 0; i < foodListSelected.length; i++) {
    print('Second Sel Food Date: ' + DateFormat('E-MM-yyyy hh:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(foodListSelected[i].eatenDateTime)));
    foodListSelected[i].set_selected = false;
    _updateEatenFood(foodListSelected[i]);

  }

1 个答案:

答案 0 :(得分:1)

您正在两个列表中存在的同一对象上调用mutator方法。如果要为第二个列表创建新的对象副本,则应编写一个克隆当前对象的方法,并在第一个循环中使用该方法。