value_state

pub package License: MIT

Test codecov

A dart package that helps to implement basic states such as initial, success and error.

🔥 Features

This package helps you manage the different states your data can have in your app (like loading, success, or error). It makes your code cleaner and easier to understand, especially when dealing with things like network requests, storage loading or complex operations.

It provides a way to represent a value that can be in one of three states:

  • initial
  • success
  • failure

🚀 Quick start

final valueInitial = Value<int>.initial();
final state = valueInitial.state; // ValueState.initial
final isInitial = valueInitial.isInitial; // true

final valueSuccess = Value.success(1);
final isSuccess = valueSuccess.isSuccess; // false
final isFailure = valueError.isFailure; // false
print('Data of value : ${valueSuccess.data}'); // Data of value : 1

When the value is in a specific state

value.when(
  initial: () => print('initial'),
  success: (data) => print('success: $data'),
  failure: (error) => print('failure: $error'),
  orElse: () => print('orElse'),
);

Map the value to a different type

valueInitial.map(
  initial: () => 'initial',
  success: (data) => 'success: $data',
  failure: (error) => 'failure: $error',
  orElse: () => 'orElse',
);

Merge two values with different types

value1.merge<int>(value2, mapData: (value) => value.length);

Value error

Map a Value to failure with actual data if any. There is no Value.failure constructor to prevent developers from forgetting to retain the data from a previous state of the Value.

final valueError = Value.initial().toFailure(Exception('error'));

print('Data of value : ${valueError.data}'); // Data of value : null
print('Error of value : "${valueError.error}"'); // Error of value : "Exception: error"

The new value from call toFailure on valueSuccess keep previous data. It provides a simple way to display both error and previous data (for example a refresh failure).

final valueErrorWithPreviousData = valueSuccess.toFailure(Exception('error'));

print('Data of value : ${valueErrorWithPreviousData.data}'); // Data of value : 1
print('Error of value : "${valueErrorWithPreviousData.error}"'); // Error of value : "Exception: error"

Handle states (isFetching, success, error...) while an action is processed

const value = Value<String>.initial();
print(value);
value.fetchFrom(() async => "result").forEach(print);
// Result :
// Value<String>(state: ValueState.initial, isFetching: false)
// Value<String>(state: ValueState.initial, isFetching: true)
// Value<String>(state: ValueState.success, isFetching: false, data: result)

License

MIT License

See the LICENSE file for details.

Feedback

Please file any issues, bugs or feature requests as an issue on the Github page.

Libraries

value_state