Home > Back-end >  Future<Map<String, dynamic>> Type issue when using a function
Future<Map<String, dynamic>> Type issue when using a function

Time:08-31

I have a call I am making to my Firebase db to return a document to get data from:

                        final docRef = db
                            .collection("GearLockerItems")
                            .doc(itemIDList[index]);
                        var doc = await docRef.get();
                        final data = doc.data() as Map<String, dynamic>;

                        String itemWeight = data['itemWeight'];
                        String itemWeightFormat = data['itemWeightFormat'];

After testing the code and knowing that it works, I wanted to create a function in order to clean up the code and make it easier to read. The function I created looks like this:

Future<Map<String, dynamic>> getItem(
    itemIDList, index) async {
  final docRef = db.collection("Items").doc(itemIDList[index]);
  var doc = await docRef.get();
  final data = doc.data() as Map<String, dynamic>;

  return data;
}

And then I call the function back in my main code with:

Future<Map<String, dynamic>> data = getGearLockerItemInStream(itemIDList, index);

But then when I try and use data as I did earlier to get the individual values like this:

String itemWeight = data['itemWeight'];
String itemWeightFormat = data['itemWeightFormat'];

I know get this error:

The operator '[]' isn't defined for the type 'Future<Map<String, dynamic>>'.
Try defining the operator '[]'

I think the issue is with my types. I struggled on what type I was returning here in the function as I had never used as Map<String, dynamic>; before. The as concept was new to me. Its type casting I believe so I tried to use that type for the function but then struggled in the main code on the type for the data variable.

CodePudding user response:

At first you should await for result because getItem is a async function, so change this:

await getGearLockerItemInStream(itemIDList, index);

because you do await the result wont be a Future anymore so you need to change data type to Map<String, dynamic>>, so your final changes should be like this:

Map<String, dynamic> data = await getGearLockerItemInStream(itemIDList, index);
  • Related