flutterdartuser-interfacelistviewwidget

How to add new element in exist element of ListView or create new ListView element?


I have the following situation: I want to create a ListView that contains collections are sorted by date. So, I have a question: how to add a new element of list to an existing widget or create a new widget (if widget that should store elements with this date is not exist) and add an element to it?

enter image description here

I know how to use ChangeNotifierProvider, ChangeNotifier and Consumer for updating UI, but I have no idea how to use it in my situation.
It can be easy or I have not correct idea, but I am new in Flutter, so I am sorry for it.

I tried to add dividers to my ListView, but they depend on the index, so when I scroll the ListView it doesnt work correctly, because I want it to depend on date, not only index.


Solution

  • If i understand your problem correctly, you need to display list of elements with Date and other information, something like this:

    20.02.2024
      element A
      element B
      element C
    ------------
    21.02.2024
      element A
      element B
      ...
    ------------
    ...
    

    To do this you will need several classed, for example Element and DateWithElements:

    class Element {
      final String name;
    
      Element(this.name);
    }
    
    class DateWithElements {
      final DateTime date;
      final List<Element> elements;
    
      DateWithElements(this.date, this.elements);
    }
    

    Then you can use them to store your data in State of your Statefull Widget(don't forget to initialize the variable with data)

    final list = <DateWithElements>[];
    

    and use variable for build widgets:

    ListView.separated(
      shrinkWrap: true,
      itemCount: list.length,
      itemBuilder: (_, index) {
        final current = list[index];
        return Column(
          children: [
            Text(current.date.toString()),
            ...current.elements.map((e) => Text(e.name)),
          ],
        );
      },
     separatorBuilder: (_, __) => const Divider(),
    

    ),

    For adding new items to list you will need a function:

    Future<void> addItem(DateTime date, List<String> elements) async {
        final newItem = DateWithElements(
          date, 
          elements.map(Element.new).toList(),
        );
        list.add(newItem);
        setState(() {});
      }