schultek / dart_mappable

Improved json serialization and data classes with full support for generics, inheritance, customization and more.
https://pub.dev/packages/dart_mappable
MIT License
148 stars 22 forks source link

help: updating nested collections and values #230

Open lukepighetti opened 1 week ago

lukepighetti commented 1 week ago

I found the ListCopyWith interface and the CopyWith topic but I'm having a hard time understanding the best approach to reduce this code into something easier to read and write.

appState.copyWith(
  timeline: [
    for (final e in value.timeline)
      if (e.id == timelineMealId)
        timelineMeal.copyWith(
          meal: timelineMeal.meal.copyWith(
            items: [
              for (final item in timelineMeal.meal.items)
                if (item.id == itemId) x.copyWith(ignore: ignore) else x
            ],
          ),
        )
  ],
);

operations

  1. given String timelineMealId, String itemId, and bool ignore
  2. update appState.timelineMeal(where id == timelineMealId).meal.items(where id == itemId).ignore = ignore

was hoping for something like

appState.copyWith.timeline.where((e)=>e.id == timelineMealId).items.where((e)=>e.id == itemId).copyWith(ignore: ignore)

schultek commented 1 week ago

The .where of the List opyWith actually filters the elements. Maybe a .select would be cool to select items and then apply changes to only those, without modifying the other items.

You can wrap the .$update method for this.