felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.76k stars 3.39k forks source link

Updating only one class member of state #2541

Closed JakeHadley closed 3 years ago

JakeHadley commented 3 years ago

Hey Felix, great package, trying to learn flutter and bloc is helping a ton. I've gotten through implementing bloc no problem, but I have a question about complex state that I haven't been able to find many answers for on the interwebs. I have a state object that I'm wanting to have a few class members on. When I start the app, I want all members of the state object to be initialized and that state returned. Later on, I want to update that state object, but only updating one of the class members. Is this an anti-pattern of sorts?

Some example code here:

class BusDataBloc extends Bloc<BusDataEvent, BusDataState> {
  final BusLocationService _busLocationService;

  BusDataBloc(BusLocationService busLocationService)
      : _busLocationService = busLocationService,
        super(DataLoading());

  @override
  Stream<BusDataState> mapEventToState(BusDataEvent event) async* {
    if (event is InitData) {
      //fetch buses
      //fetch routes
      //fetch detours
     yield DataLoaded(*/all the stuff*/);
    } else if (event is GetData) {
     //fetch only buses
      List<Bus> buses = await _busLocationService.getParsedBuses();
      //yield old stuff with the new set of buses
      yield DataLoaded(buses: buses);
    }
  }
}

What's the best way to go about this?

felangel commented 3 years ago

Hi @JakeHadley 👋 Thanks for opening an issue

You can define a copyWith to easily create a copy of your state with one or more updated properties. You can take a look at the weather app for an example https://github.com/felangel/bloc/blob/76268b3e2b7184d79563811eb084cc36efba1e3c/examples/flutter_weather/lib/weather/cubit/weather_state.dart#L27

Hope that helps 👍

JakeHadley commented 3 years ago

Oh, yeah. That helps a lot. Thanks!