listobjectflutterlistviewreorderable-list

Flutter ReorderableListView with custom object


I am currently having a few difficulties with ReorderableListView.

I have a list of ToDoPrefabs, which I want to output, because my list does not consist of strings but something else, I get errors in the index, for the key and the text.

this is the error:

"type 'To Prefab' is not a subtype of type 'int'"

I suspect that this is the key. It is also logical since todoprefab is not an int. Does anyone have an idea how I can get another index of the type int in my ReorderableListView

This is my ReorderableListView

return ReorderableListView(
      onReorder: _onReorder,
      scrollDirection: Axis.vertical,
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      children: [
        for(final item in toDoManagerClass.todoBank)
        todocardprefab(item)
      ]
    );

the todocardprefab (not the list)

todocardprefab(var key){
  return Dismissible(
    key: ValueKey(key),
    background: Container(color: Colors.red, alignment: Alignment.centerLeft, child: Icon(Icons.delete),),
    secondaryBackground: Container(color: Colors.green, alignment: Alignment.centerRight, child: Icon(Icons.archive),),
    child: Card(
      child: ListTile(
        //leading: Icon(Icons.check_box_outline_blank),
        title: Text(toDoManagerClass.todoBank[key].toDoText),
        onTap: (){},
      ),
    ),
  );
}

and this is the simple list.

class ToDoManagerClass{
  List<ToDoPrefab> todoBank = [
    ToDoPrefab(text: 'Homework', f: false),
    ToDoPrefab(text: 'Homework1', f: false),
    ToDoPrefab(text: 'Homework12', f: false),
    ToDoPrefab(text: 'Homework123', f: false),
    ToDoPrefab(text: 'Homework1234', f: false),
    ToDoPrefab(text: 'Homework12345', f: false),
  ];
}

Solution

  • This method should work:

    Your reordable listview

    return ReorderableListView(
          onReorder: _onReorder,
          scrollDirection: Axis.vertical,
          padding: const EdgeInsets.symmetric(vertical: 8.0),
          children: [
            for(final item in toDoManagerClass.todoBank)
            todocardprefab(item, index())
          ]
        );
    

    and here the function. It returns a number higher with each call.

    int index(){
        if(i < toDoManagerClass.todoBank.length){
          print(i);
          i++;
        }
        return i-1;
      }
    

    now you only have to use the index instead of the item in your todocard