Basic Usage
Let's continue with our Weather example (you can find it here).
The super-sealed classes (Weather, ValidWeather, InvalidWeather and InvalidWeatherValue) replicate the same functionality of modddels :
// NB : In these examples, the types of the variables/callback parameters is specified
// only for the sake of showing their types to you. You don't need to do so.
final Weather weather = Weather.rainy(
temperature: 12,
rainIntensity: 0.9,
);You can use isValid, toEither and toBroadEither :
bool isValid = weather.isValid;
Either<InvalidWeather, ValidWeather> either = weather.toEither;
Either<List<Failure>, ValidWeather> broadEither = weather.toBroadEither;All pattern matching methods we've seen so far can be used too : map, mapValidity, maybeMap, mapOrNull, maybeMapValidity, mapInvalid, whenInvalid, etc... :
final message1 = weather.map(
valid: (ValidWeather validWeather) => 'This weather is habitable',
invalidValue: (InvalidWeatherValue invalidWeatherValue) =>
invalidWeatherValue.habitableFailure.when(
tooHot: () => "Humans would die of heat",
tooCold: () => "Humans would freeze to death",
),
);
final message2 = weather.mapValidity(
valid: (ValidWeather validWeather) => 'Valid weather',
invalid: (InvalidWeather invalidWeather) => 'Invalid weather',
);You can also access the failure(s) :
weather.mapOrNull(
invalidValue: (InvalidWeatherValue invalidWeatherValue) {
WeatherHabitableFailure failure = invalidWeatherValue.habitableFailure;
},
);Last updated