Skip to content

Instantly share code, notes, and snippets.

@GIfatahTH
Created May 28, 2020 08:24
Show Gist options
  • Save GIfatahTH/016a4fb9937f4e727c15e871268d81e0 to your computer and use it in GitHub Desktop.
Save GIfatahTH/016a4fb9937f4e727c15e871268d81e0 to your computer and use it in GitHub Desktop.
@immutable
class CatalogState {
CatalogState({
@required this.repository,
@required this.items,
});
//
final CatalogRepository repository;
final List<Item> items;
//After getting items from the repository,
//A new CatalogState is return with the
Future<CatalogState> getItems() async {
final items = await repository.fetchItems();
return copyWith(
items: items,
);
}
static Stream<CatalogState> deleteItem(
CatalogState currentState,
Item item,
) async* {
try {
//yield the new state.
//states_rebuilder will refresh the UI to display the new state
yield currentState.copyWith(
items: currentState.items.where((e) => e.id != item.id).toList(),
);
//remove the item from the backend
await currentState.repository.removeItem(item);
} catch (e) {
//on error, yield the old state
//states_rebuilder will refresh the UI to display the old state
yield currentState;
//rethrow the error; states_rebuilder will catch the error
//display a SnackBar.
rethrow;
}
}
CatalogState copyWith({
List<Item> items,
CatalogRepository repository,
}) {
return CatalogState(
items: items ?? this.items,
repository: repository ?? this.repository,
);
}
}
//This is the initial state.
class CatalogInitialState extends CatalogState {
CatalogInitialState(CatalogRepository repository)
: super(
items: [],
repository: repository,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment