2

I use Either to fetch data by REST API as below:

Future<Either<ResponseError, List<ResponseApi>>> getApi() async {
  ...
  if (ERROR) {
    return Left(ERROR);
  else {
    return Right(RESPONSE);
  }

Then I want to get data as below:

FutureBuilder _getPhonebooks() {
  return FutureBuilder<Either<ResponseError, List<ResponsePhonebook>>>(
    future: RequestGetPhonebook().getPhonebooks(),
    builder: (
      BuildContext context, AsyncSnapshot<Either<ResponseError, List<ResponsePhonebook>>> snapshot) {
      if (snapshot.hasData) {
        return _cerateData(snapshot.data);
      }
      else {
        ...
      }

Then I do it in _createData() as below:

Widget _cerateData(Either<ResponseError, List<ResponseApi>> data) {
  return data.fold((l) {
    return Text(l.error + '\n' + l.errorDescription);
  }, (r) {
    return ListView.builder(
      itemCount: r.length,
      itemBuilder: (context, index) {
        return _tile(r[index].lastName + r[index].firstName, r[index].reading, Icons.work);
      });
  });
}
mikezang
  • 2,291
  • 7
  • 32
  • 56

0 Answers0