cannot access members of tuple in future builder in flutter

Issue

I have a Tuple which has two members: List<DeliveryAddressModel> and ApiResponseCode. The code is as follows:

  Future<Tuple2<List<DeliveryAddressModel>, ApiResponseCode>> getAddressList() async {
    int retry  0;
    List<DeliveryAddressModel> deliveryAddressList  [];
    while (retry++ < 2) {
      try {
        deliveryAddressList 
            await CoreRepo.instance.getCoreClient().getDeliveryAddresses();

        for (int i  0; i < deliveryAddressList.length; i++) {
          print("inside core repo: ${deliveryAddressList[i].addressTitle}");
        }
        return Tuple2(deliveryAddressList, ApiResponseCode.SUCCESS);
      } catch (e) {
        CoreRepo.instance.getCoreClient().getDeliveryAddresses();
      }
    }
    return Tuple2(deliveryAddressList, ApiResponseCode.SERVER_ERROR);
  }

Now inside some other page I need to show the data, more specifically List<DeliveryAddressModel>.

So this is what I tried:

  body: FutureBuilder(
    future: CoreRepo.instance.getAddressList(),
    builder: (context, snapshot) {
      if (snapshot.data  null) {
        return LoadingWidget(
          status: "Loading your delivery addresses",
        );
      }
      if (snapshot.data.item2  ApiResponseCode.FAILED) { > ERROR 1
        return Text("Failed");
      }
      return RefreshIndicator(
        backgroundColor: Colors.black,
        child: buildFeed(snapshot.data.item1), > ERROR 1
        onRefresh: () > refreshList(context),
      );
    },
  ),

ERROR 1:

The property 'item2' can't be unconditionally accessed because the receiver can be 'null'.

Try making the access conditional (using '?.') or adding a null check to the target ('!').

This comes straight from the documentation of tuple:

const t Tuple2(‘a’, 10);

print(t.item1); // prints ‘a’ print(t.item2); // prints ’10’

For more info: core_repo, core_client, delivery_list_page

Solution

Because the snapshot data itself could be null you should safely access its value

snapshot.data?.item2

Also you need modify future builder

FutureBuilder<Tuple2<List<DeliveryAddressModel>, ApiResponseCode>>>

because future builder can not infer the data type you should provide it your self

Answered By – Hosam Hasan

Leave a Comment