felangel / equatable

A Dart package that helps to implement value based equality without needing to explicitly override == and hashCode.

Home Page:https://pub.dev/packages/equatable

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

I should use final, but what if I need to modify something instead?

EmanueleVinci opened this issue · comments

Hi! I'm new with equatable and I've red that all the parameters in my model must be final, but I don't know how to deal with it...
What if i need to modify one of these parameters? I've a view where you can add new restaurants to a list, and this list will be saved in Firestore. I'm using flutter bloc, so I add a CreateRestaurantFirebaseEvent, and this is what happens in my mapEventToState:

if (event is CreateRestaurantFirebaseEvent) 
      await _databaseService.createRestaurant(event.restaurant, event.user);
      List<Restaurant> restaurantsList = await _databaseService
          .loadRestaurantsList(event.user.restaurantsIDsList);
      yield LoadedRestaurantsListState(restaurantsList);
    }

and in my database_service:

  Future createRestaurant(Restaurant restaurant, User user) async {
    restaurant.adminId = user.id;
    DocumentReference restaurantDoc =
        await restaurantCollection.add(restaurant.toMap());
    user.restaurantsIDsList.add(restaurantDoc.id);
    updateUser(user);
    restaurant.id = restaurantDoc.id;
    return restaurant;
  }

So, I've to update my restaurant with some props, but if I've only final props I can't do that. What is the best practice? I need equatable, otherwise my bloc won't work correctly.

Thanks in advance

Hi @Ozymandias93 👋
Thanks for opening an issue!

You can define a copyWith method on your class and instead of trying to modify the instance create a new instance with the updated values using copyWith. You can check out https://github.com/felangel/bloc/blob/c1fc3b8b8484265ec75fd208f58588d809ed7d17/examples/flutter_infinite_list/lib/posts/bloc/post_state.dart#L16 as an example.

Hope that helps 👍