Use Either<> from fpdart to enhance your Dart code
Use the power of functional programming to take your dart code to the next level
4 min readJul 29, 2023
At a beginner level, let’s say you have a function with an API call for fetching the list of users inside a repository, something like this:
Future<List<User>> getUsers() async {
var url = Uri.parse(‘https://jsonplaceholder.typicode.com/users');
var response = await http.get(url);
var list = jsonDecode(response.body) as List;
return list.map((e) => UserJson.fromJson(e).toDomain()).toList();
}
For consuming this, your BLoC/Provider/Cubit or any other state management page-couple would probably look something like this:
Future<void> fetchUsers() async {
emit(state.copyWith(isLoading: true));
try {
final users = await usersRepository.getUsers();
emit(state.copyWith(users: users, isLoading: false));
} catch (ex) {
// print or log your error
emit(
state.copyWith(
error: MyErrorClass(errorString: ex.toString()),
isLoading: false,
),
);
}
}
And given your app’s pages, features, API calls, it’s going to get blotchy when you have a lot of BLoC/Cubit/Provider files with lots of API calls. Furthermore, this BLoC/Cubit/Provider should not worry about…