Hi,
I am using single state concept in my project like (your below example). It is very easy and useful for me. But i want to know What is purpose, How to use and Where to use of "copyWith" function. Can you please give me some sample code for that.
Example code:
`
class NewCarState {
final List
final String brand;
final List
final String model;
final List
final String year;
const NewCarState({
@required this.brands,
@required this.brand,
@required this.models,
@required this.model,
@required this.years,
@required this.year,
});
bool get isComplete => brand != null && model != null && year != null;
factory NewCarState.initial() => NewCarState(
brands:
brand: null,
models:
model: null,
years:
year: null,
);
factory NewCarState.brandsLoading() => NewCarState(
brands:
brand: null,
models:
model: null,
years:
year: null,
);
factory NewCarState.brandsLoaded({
@required List
}) =>
NewCarState(
brands: brands,
brand: null,
models:
model: null,
years:
year: null,
);
factory NewCarState.modelsLoading({
@required List
@required String brand,
}) =>
NewCarState(
brands: brands,
brand: brand,
models:
model: null,
years:
year: null,
);
factory NewCarState.modelsLoaded({
@required List
@required String brand,
@required List
}) =>
NewCarState(
brands: brands,
brand: brand,
models: models,
model: null,
years:
year: null,
);
factory NewCarState.yearsLoading({
@required List
@required String brand,
@required List
@required String model,
}) =>
NewCarState(
brands: brands,
brand: brand,
models: models,
model: model,
years:
year: null,
);
factory NewCarState.yearsLoaded({
@required List
@required String brand,
@required List
@required String model,
@required List
}) =>
NewCarState(
brands: brands,
brand: brand,
models: models,
model: model,
years: years,
year: null,
);
NewCarState copyWith({
List
String brand,
List
String model,
List
String year,
}) {
return NewCarState(
brands: brands ?? this.brands,
brand: brand ?? this.brand,
models: models ?? this.models,
model: model ?? this.model,
years: years ?? this.years,
year: year ?? this.year,
);
}
}`
Thanks,
Ganesh. S
Hi @GaneshSingaravelu 馃憢
copyWith is a pattern used when working with immutable objects; it allows to create a new instance while also preserving unspecified values from an existing instance.
yield state.copyWith(brand: 'brand new brand(couldn't help myself)');
This will create a new instance of NewCarState with your new specified brand AND will also copy all other existing values from the previous instance.
Hope it makes sense 馃憤
Most helpful comment
Hi @GaneshSingaravelu 馃憢
copyWithis a pattern used when working with immutable objects; it allows to create a new instance while also preserving unspecified values from an existing instance.This will create a new instance of
NewCarStatewith your new specified brand AND will also copy all other existing values from the previous instance.Hope it makes sense 馃憤