Guide to transforming an IdentityMap<String, dynamic> into a UInt8List

I have a cloud function that generates a JavaScript Buffer object, which looks something like this:

functions
        .region("europe-west2")
        .runWith({ timeoutSeconds: 20, memory: "128MB", })
        .https
        .onCall(async (data, context) => {
           const buffer = await sharp(imagePath).toBuffer();
           return buffer;
        });

In my code repository, I interact with this cloud function in the following way:

  Future<Uint8List> resizeImage({required String fileName}) async {
    try {
      final result = await firebaseFunctions
          .httpsCallable('resizeImage')
          .call<dynamic>({'fileName': fileName});

      //printing result.data returns an IdentityMap<String, dynamic>.
    } on FirebaseFunctionsException catch (e) {
      //handle error
    }
  }

Whenever I print result.data.runtimeType, it shows as a map object with values like this :

{12: 239, 2938: 293}

How can I convert this map into a UInt8List?

Answer №1

After some investigation, I realized that I needed to extract the values from the IdentityMap and convert them into a List.

The data returned wasn't {12: 239, 2938: 293}, but rather {0: 239, 1: 293, 2:382}, indicating it was index-based. To resolve this issue, I did the following:

      final bytes = List<int>.from(result.data.values);
      return Uint8List.fromList(bytes);

Answer №2

It is important to note that the order of values in a map is not guaranteed. Your approach may yield results depending on the implementation, but the following code does not rely on the assumption that the map's values will be iterated in the correct order:

Uint8List bytes = Uint8List(result.data.length);
for (var key in result.data.keys) {
  bytes[int.parse(key)] = result.data[key];
}

If the keys are not strings, there is no need to parse them into integers unless necessary, as was the case with mine.

Furthermore, it is worth mentioning that returning the buffer may work, but a more optimal solution would be to return base64 encoded bytes. This encoding leads to fewer bytes being transmitted over the network connection.

In the cloud function:

return buffer.toString('base64');

In the application:

Uint8List bytes = base64.decode(result.data);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to resolve the issue of incompatible parameters 'action' types in JavaScript

I'm encountering a common problem, but I can't figure out why this error is happening. After updating redux, I encountered the following error message: TS2322: Type '(state: ILanguage | undefined, action: PayloadAction<ILanguage>) =&g ...

Exploring the world of mocking tests using Jest and inputs

Is there a way to create a jest test specifically for this function? const input = require('prompt-sync')(); export function choices(): void { const choice = input("Choose a letter"); if (choice === "a") { con ...

The issue of "ReferenceError: Cannot access '<Entity>' before initialization" occurs when using a OneToMany relationship with TypeORM

There are two main actors involved in this scenario: User and Habit. The relationship between them is defined by a OneToMany connection from User to Habit, and vice versa with a ManyToOne. User Entity import {Entity, PrimaryGeneratedColumn, Column, Creat ...

Issue with OpenAI's Rate Limit 429 Restriction

I've been experimenting with this repository in order to implement semantic search for YouTube videos using OpenAI + Pinecone. However, I keep encountering a 429 error at the following step - "Run the command npx tsx src/bin/process-yt-playlist.ts to ...

I'm currently utilizing CSS GRID to create a map layout, but I'm encountering an issue where the layout is not filling the entire screen. I'm wondering how I can achieve this in Angular

Here is the unique html code snippet for a layout that dynamically creates grids using json input: <!DOCTYPE html> <html lang="en"> <head> <title>Booking Page</title> </head> <body> <div ...

How to implement and utilize a history-object interface in React with Typescript?

Can you help me with setting up an interface for a history object in my component? Currently, it is typed as any and I want to type it appropriately. Object: Here's the code snippet: import React, { useState } from 'react'; import { Row, C ...

Rxjs error: The 'pipe' property is not found on the 'UnaryFunction<Observable<{}>, Observable<string | {}>>' type

Currently working on implementing ngbTypeAhead and encountering problems with RxJS version 5.5.5. The example I am referencing is from version 6 of rxjs. "rxjs": "^5.5.2" and angular "^5.0.1", "typescript": "~2.6.1", While trying to apply typeahead on f ...

Angular - Leveraging Jest and NgMocks to Mock Wrapper Components

Within our project, we have implemented a feature where user roles can be assigned to various elements in the application. These roles determine whether certain elements should be disabled or not. However, due to additional conditions that may also disable ...

Error: setPosition function only accepts values of type LatLng or LatLngLiteral. The property 'lat' must be a numerical value in agm-core agm-overlay

Currently, I am utilizing Angular Maps powered by Google @agm-core and agm-overlay to implement custom markers. However, when using the (boundsChange) function on the agm-map component, an error occurs with the message "invalidValueError: setPosition: not ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...

Utilizing custom hooks for passing props in React Typescript

I have created a unique useToggler custom hook, and I am attempting to pass toggle props from it to the button child in the Header component. However, when I try using toggle={toggle}, I encounter this error: Type '{toggle: () => void;}' is ...

The 'target' property is not found on the type 'KeyboardEventHandler<HTMLInputElement>'

My Visual Studio Code is giving me an error in my onKeyUp function when I try to access the input target and retrieve its value. import React from 'react'; import styles from './styles.module.scss'; export function Step3() { ...

Tips for resolving the issue of 'defineExpose' method being undefined in Vue3

Struggling to pass a method from child to parent; unfortunately, the defineExpose() method seems to be malfunctioning. Could anyone provide guidance on what might be going wrong? For additional context, feel free to check out my previous question <scri ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Convert potentially undefined boolean into a boolean by utilizing "!!"

Just had a thought - when dealing with a potentially undefined boolean variable, is it advisable to cast it as a boolean using the double exclamation mark? Consider this interface: interface Example { id: number; isDisabled?: boolean; } We then have ...

Nextjs 14 experiences full page loading due to the presence of multiple root layouts

The issue I'm facing involves a full page load when navigating between two root layout pages In my Next.js application (NextJS 14), I have created two root layouts. However, when moving from the first layout to the second layout, it triggers a comple ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...

What is the best way to refresh or reload a child component in Angular?

I have a transaction.component.html file that displays the app-deal-partners component. Every time the delete function is triggered, I want to refresh and reload the child component, which is the app-deal-partners component. I need to reload <app-deal- ...

Mastering Angular 2 Reactive Forms: Efficiently Binding Entire Objects in a Single Stroke

Exploring reactive forms in Angular 2 has led me to ponder the possibility of binding all object properties simultaneously. Most tutorials show the following approach: this.form = this.fb.group({ name: ['', Validators.required], event: t ...

Utilizing TypeScript Generics for Creating Arrays of Objects with Inherited Type Definitions

I'm exploring the concept of type inheritance for an array of objects, where one object's value types should inherit from another. While I'm unsure if this is achievable, it's definitely worth a try. Currently, I believe my best approac ...