skip to Main Content

So I have a function that concurrently fetches two diffrent object models , but i’m having a problem trying to display these values by their respective models . So below is where I’m fetching the data that I want to display:

final getProfileAndItem = FutureProvider.family((ref, String uid) async {
  return ref.watch(itemUserProvider).getItemByUser(uid);
});

 Future<(UserTable, ItemModel)> getItemByUser(String uid) async {
    try {
      final value = await Future.wait([
        http.get(Uri.parse('${API.getpurchaseItemByUID}' '?uid=$uid')),
        http.get(Uri.parse('${API.getUserProfileByUID}' '?uid=$uid'))
      ]);

      final item = jsonDecode(value[0].body); 
      final profile = jsonDecode(value[1].body);

      return (UserTable.fromJson(profile[0]), ItemModel.fromJson(item[0]));
    } catch (error) {
      throw error;
    }
  }

Below is where i’m trying to display the data and where i’m getting the error ,it seems that every time I try to fetch a value by the model it belongs to I get The getter isn't defined for the type '(UserTable, itemModel)'.

 ref.watch(getProfileAndItem(uid)).when(
              data: (data) => Column(
                  children: [
                    Text(data.userName),//UserTable
                    Text(data.itemName)//ItemModel
                  ],
                ),
              error: (error, stackTrace) => ErrorText(error: error.toString()),
              loading: () => const Loader(),
            ));

2

Answers


  1. Since data is a Record (type '(UserTable, itemModel)'), if you want to get userName and itemName from the ItemModel (which is the second value in the Record), you should access them like this:

    data: (data) => Column(
      children: [
        Text(data.$2.userName),
        Text(data.$2.itemName)
      ],
    ),
    
    Login or Signup to reply.
  2. The error notice, "The getter isn’t defined for the type (UserTable, itemModel)," is because you’re attempting to access attributes of a tuple (UserTable, ItemModel) directly as if it were an object of a certain model. Because a tuple is not a named object, you must use indexing (e.g., data.item1 or data.item2) to access its attributes. Here’s how you can change your code to properly access the properties:

    ref.watch(getProfileAndItem(uid)).when(
      data: (data) => Column(
        children: [
          Text(data.item1.userName), // Access userName from UserTable
          Text(data.item2.itemName), // Access itemName from ItemModel
        ],
      ),
      error: (error, stackTrace) => ErrorText(error: error.toString()),
      loading: () => const Loader(),
    ));
    

    data.item1 accesses the first item in the tuple (UserTable, ItemModel), which is your UserTable instance, and data.item2 accesses the second item in the tuple, which is your ItemModel instance, in this code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search