The Answer package simplifies the handling of function returns by allowing them to return either a success or an error object. This enhances code readability and makes error handling more structured.
To use the package in your Flutter project, simply add the dependency to your pubspec.yaml:
dependencies:
answer: ^0.0.1Import the package in your code:
import 'package:answer/answer.dart'; Future<Answer<AnswerFailure, String>> getUserId() async {
try {
final result = await loginDatasource.getUserId();
return Answer.success(result);
} catch (e) {
return Answer.fail(e);
}
} Future<Answer<AnswerFailure, String>> getUserId() async {
try {
final result = await loginDatasource.getUserId();
return result.asAnswer();
} catch (e) {
return e.asAnswer();
}
} Future<void> login() async {
final answer = await getUserId();
answer.deal(
onSuccess: (idUser) {
print(idUser);
},
onError: (error) {
print(error);
},
);
} Future<String> login() async {
final answer = await getUserId();
return answer.deal(
onSuccess: (idUser) {
return idUser;
},
onError: (error) {
return error.message;
},
);
}We recommend that you use the class AnswerFailure as the default response for Failure, this guarantees that your returns will always have a pattern, if you need a specific error, create a new error extending the class Answer Failure
class MyError extends AnswerFailure {
MyError() : super(
message: 'MyError',
code: 1,
);
}Add AnswerFailure as your return in case of errors
Future<Answer<AnswerFailure, String>> getUserId() async {
try {
final result = await loginDatasource.getUserId();
return Answer.success(result);
} catch (e) {
return Answer.fail(MyError());
}
} Future<void> login() async {
final answer = await getUserId();
answer.deal(
onSuccess: (idUser) {
print(idUser);
},
onError: (error) {
if (error is MyError) {
print(error.message);
}else{
print(error.message);
}
},
);
}You can also use TypeDef AnswerDefault simplifying the parameters, it by default returns AnswerFailure and you just need to pass the success object
Future<AnswerDefault<String>> getUserId() async {
try {
final result = await loginDatasource.getUserId();
return Answer.success(result);
} catch (e) {
return Answer.fail(e);
}
}Some Mocks libraries for testing contain import name conflicts, in these cases it is recommended that you import the Mocks library with the Hide Answer instruction.
import 'package:answer/answer.dart';
import 'package:mocktail/mocktail.dart' hide Answer;
void main() {
test('test', () {
...
});
}