如何在 StateNotifier 中将列表复制到另一个列表中,以便每次更改时都会更新

问题描述

列表 EleccionSinSeleccionClase 只是一个包含字符串的类的列表。

--traceback         always print a traceback on exception

状态列表是另一个类:

class EleccionSinSeleccionClase {
  String Eleccion;
}

问题是我想把第一个复制到StateNotifier的状态中,这一行破坏了代码。 这是一行:state[i].Eleccion = ListaElecciones[i].Eleccion;

class EleccionConSleccionClase {
  String Eleccion;
  bool selec;
}

解决方法

也许问题在于您将状态初始化为空列表 super([]),然后您试图更改不存在的索引中的值(state[i] 列表显然为空并且无法访问该位置)

void init(){
    print(ListaElecciones.length.toString());
    if(ListaElecciones.length != 0){
      /// you will need to check if both lists are the same lenght if you actually want to do this
      /// without failling
      /*for (int i = 0; i < ListaElecciones.length; i++) {
        state[i].Eleccion = ListaElecciones[i].Eleccion;  ////HERE////
      }*/
      /// if you only want to copy Eleccion parameter in a new class this would be the easiest way
      state = ListaElecciones.map((cb) => EleccionConSleccionClase(Eleccion: cb.Eleccion)).toList();
    }
  }