Flutter add remove widget from tree generated from Nested Lists or list of lists object that is needed to be updated

779 views Asked by At

I have an object structure that has nested list of same type of objects. as follows :

class NoteModel {
  String id;
  String data;
  List<NoteModel> children;

  NoteModel({
    this.id,
    this.data,
    List<NoteModel> children,
  }) : children = children ?? [];
}

and a sample data structure as follows :

var _result = NoteModel(
      id: 'main Head',
      data: 'main Head Data',
      children: [
        NoteModel(
          id: ' child 1',
          data: 'child 1 data',
          children: [],
        ),
        NoteModel(
          id: 'child 2',
          data: 'child 2 data',
          children: [
            NoteModel(
              id: 'subchild 1',
              data: 'subchild 1 of child 2',
              children: [],
            ),
          ],
        ),
        NoteModel(
          id: 'child 3',
          data: 'child 3 data',
          children: [],
        )
      ],
    );

and [Custom Widget] that would show 'id', 'data' and a list of [Custom Widget]s using this structure. my problem arise when I try to Add (button on parent widget that would add objects to children) or remove (button on child widget that would remove itself from the children list of parent).

the object instance of NoteModel is changing on press of button however the list tree is not refreshing. I have tried all manual methods, and tried to use GetX. However I can't find a solution that would trigger rebuild of the widget tree with updated instance of NoteModel, when some widget is added/removed from deep within the tree.

in this rebuild process however i would like to only rebuild certain parts to avoid rebuilding other parts for example any button in child [custom Widget] that would not change.

please help, I am new to this, tried many things but can't find any solution to add/remove operation in nested children.

1

There are 1 answers

0
Younss AIT MOU On

Your question revolves around widget state updates. Your code snippet is not complete. So I don't know if you are using a StatefullWidget or a StatelessWidget. Nevertheless, if you want to update the widget tree upon data changes you have two options:

  • Using a StatefullWidget and calling setState((){}) everytime you update a piece of data.
  • Using a state management package such as flutter_bloc. Widgets that are wrapped in a BlocBuilder will get updated whenever the state changes.

Personally, I would go with option 2. Using a flutter_bloc gives you more grained control over what to rebuild in the widget tree.