Either class of dartz library is used to return two type of data from a single function.
Suppose, there is an method which convert input String value in int and return it.
1 2 3 |
int convertVal(String data) { return num.parse(data); } |
Here, we can only return a int value. If we get any error and handle it in our code, still we will have to return int value only. We are not able to send error message in this case.
Check our Flutter app development services page.
Either class
If we wanna return two type of data, we can use Either class of dartz library. For this, we need to add dartz library in our project.
In above example, we can return int value as successful result and error message in failure case.
Implementation
Step 1 : Add dependency
1 |
dartz: ^0.8.9 |
NOTE : To check latest package & learn more about dartz package, check following link : dartz
Step 2 : Function implementation
Import following package :
1 |
import 'package:dartz/dartz.dart'; |
Now, wrap data which we wanna return, in Left & Right class and return them.
1 2 3 4 5 6 7 |
Either<String, int> convertVal(String data) { try { return Right(num.parse(data)); } catch(e) { return Left(e.toString()); } } |
NOTE : Here, we wrap success result in Right class and failure result in Left class. You can change them. Also, you can wrap any object class as well.
Step 3 : Handle result
1 2 3 4 5 6 7 8 |
var result = convertVal("AA33"); // pass any integer or non-integer value result.fold( (l) { // if there is any error, this block will execute print("Error: "+l); }, (r) { // if we get successful result, this block will execute print(r); }); |
Through fold method, we can handle result. For more methods of Either class, please check following link : Class-methods
You can check following link to check more blog related to flutter & dart : Blog
Hope, this blog will be helpful to you.