Append an array into Flutter Firestore - firebase

I have a List in Flutter, and I want to add the name field of the objects inside as a list into a collection called requests
List selectedAllergies = [];
However, when I do this, I get this error message:
E/flutter ( 4031): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Invalid argument: Instance of 'Allergies'
List selectedAllergies = [
Allergies(id: 1, name: "Milk"),
Allergies(id: 2, name: "Peanuts"),
Allergies(id: 3, name: "Tree Nuts"),
Allergies(id: 4, name: "Eggs"),
Allergies(id: 5, name: "Soy"),
Allergies(id: 6, name: "Wheat"),
Allergies(id: 7, name: "Shellfish"),
Allergies(id: 8, name: "Snake"),
];
class Allergies {
final int id;
final String name;
Allergies({
required this.id,
required this.name,
});
}
Is it possible to append only the "name" field of the selectedAllergies list into a document in the collection of requests?

Firestore doesn't allow adding dart objects directly. See here for a list of supported data types in Firetore.
Instead, as you suggested, we can just add the names of the allergies. The following code illustrates how to get a list of the names.
List allergyNames = selectedAllergies.map((e) => e.name).toList();
Then, you can add allergyNames to your Firestore document instead.

Related

Error getting keys from Azure Storage Account with listkeys(...) method with Bicep syntax

I have a Bicep template to create an Azure Storage Account
#description('the name of the storage account')
param name string
#description('the alias of the storage account')
param shortName string
#description('tags')
param tags object
#description('the name of the key vault resource where place output secrets')
param keyVaultName string
resource storageAccount 'Microsoft.Storage/storageAccounts#2022-09-01' = {
name: name
location: resourceGroup().location
sku: {
name: 'Standard_LRS'
tier: 'Standard'
}
kind: 'StorageV2'
tags: union(tags, {
type: 'storage-account'
})
}
Then, I need to get the keys
var keys = listkeys(storageAccount.id, storageAccount.apiVersion)
output keyObject object = keys[0]
output KeyValue string = keys[0].value
But everytime that I runs the template, I receive these errors:
{
"code": "DeploymentOutputEvaluationFailed",
"message": "Unable to evaluate template outputs: 'keyObject,keyValue'. Please see error details and deployment operations. Please see https://aka.ms/arm-common-errors for usage details.",
"details": [
{
"code": "DeploymentOutputEvaluationFailed",
"target": "keyObject",
"message": "The template output 'keyObject' is not valid: The language expression property '0' can't be evaluated, property name must be a string.."
},
{
"code": "DeploymentOutputEvaluationFailed",
"target": "keyValue",
"message": "The template output 'keyValue' is not valid: The language expression property '0' can't be evaluated, property name must be a string.."
}
]
}
The purpose of get keys is to save it into Azure Key Vault by using KeyValue var from previous step
resource keyVault 'Microsoft.KeyVault/vaults#2022-07-01' existing = {
name: keyVaultName
}
resource secret 'Microsoft.KeyVault/vaults/secrets#2022-07-01' = {
parent: keyVault
name: secretName
properties: {
value: KeyValue
contentType: 'plain/text'
}
}
So..
What's wrong with listKeys(...) method?
By following this tweet https://twitter.com/adotfrank/status/1341084692100108288?s=46&t=sWx0hvS0sS47llWLlbWZTw I found an alternative method to get keys.
Just referencing to a storage account object and use the method listKeys()
resource storageAccount 'Microsoft.Storage/storageAccounts#2022-09-01' = {
name: name
location: resourceGroup().location
sku: {
name: 'Standard_LRS'
tier: 'Standard'
}
kind: 'StorageV2'
tags: union(tags, {
type: 'storage-account'
})
}
var storageAccountKeys = storageAccount.listKeys()
Then, I can access to primary or secondary key with storageAccountKeys.keys[0].value
This fix solve my issue.

Parsing Map data into Model classes in Flutter - Firebase

I am trying to parse a map of QueryDocumentSnapshot into a model class in a flutter. Basically what I'm trying to do is get all movies into one place and Stream them to child classes without calling StreamBuilder in each widget.
class CrudModel extends ChangeNotifier{
final Stream<QuerySnapshot> _movieStream = FirebaseFirestore.instance.collection('movies').snapshots();
}
By using the following method I looking to create a List of Movies, Pass to child classes.
Stream<List<Movie>> get getListOfMovies{
return _movieStream.map((event) => event.docs.map((e) => Movie(
id: e.data()["id"] ?? 2,
title: e.data()["title"] ?? "default",
imageUrl: e.data()["imageUrl"] ?? "default",
description: e.data()["description"] ?? "default",
rating: e.data()["rating"] ?? "default",
year: e.data()["year"] ?? "default",
duration: e.data()["duration"] ?? "default",
)).toList());
}
e.data()["title"] won't let me assign the values saying receiver can be null.
I would also like to know is there any convention that I can use when streaming a list of data into child widgets using Provider?
Thank you for any help!

undefined in TypeORM and NestJS

var name = await this.productRepo.findOne({where:{id}})['name']
Hi guys. I use typeorm and sqlite to get the property name from ProductEntity but I get undefined instead.
when I try to run var name = await this.productRepo.findOne({where:{id}}) i get something like that
ProductEntity {
id: 1,
name: 'فن لپتاپ',
code: 'a57gr3f',
quantity: 2,
discription: 'ب',
price: 3000000
}
I am expected to get a فن لپتاپ instead of undefined
I'll be thankfull if you help.
await this.productRepo.findOne({where:{id}})['name']
// \____________________________________/
// this is an instance of Promise, not the resolved value
// and Promise doesn't have the property 'name'
do this instead:
( await this.productRepo.findOne({where:{id}}) )['name']

Redux-thunk - How to structure fetched data to index storage pattern?

I am using Redux + Redux-thunk to fetch datas from my API.
The data returned by my thunk is an array that looks like this :
[
{id_user: 1, name: "Joe", surname: "M", email: "joe#email.fr"},
{id_user: 2, name: "Jimmy", surname: "S", email: "jimmy#email.fr"},
{id_user: 9, name: "Jhonny", surname: "H", email: "jhonny#email.fr}
]
What I would like to do but don't get how to, is to store this data in my global state using the index storage pattern.
For exemple, from the fetched array showed above, the data structure I would like to store would look like this :
{
"usersById": {
1: {
id_user: 1,
name: "Joe",
surname: "M",
email: "joe#email.fr"
},
2: {
id_user: 2,
name: "Jimmy",
surname: "S",
email: "jimmy#email.fr"
},
9: {
id_user: 9,
name: "Jhonny",
surname: "H",
email: "jhonny#email.fr
}
}
}
Here is how I tried doing it in my success user fetch action creator :
export const fetchUsersSuccess = (users) => ({
type: types.FETCH_USERS_SUCCESS,
users: users.map(user =>
'userById': {
[user.id_user]: {
id_user: user.id_user,
name: user.name,
surname: user.surname,
email: user.email,
}
}
}),
loading: false,
});
The problem is, this still returns an array, looking like this :
[
userById: {
1: {
id_user: 1
name: "Joe"
surname: "M"
}
},
userById: {
2: {
id_user: 2
name: "Jimmy"
surname: "S"
}
},
userById: {
9: {
id_user: 9,
name: "Jhonny",
surname: "H"
}
},
]
I searched around but could not get an answer for this. I also tried to format the fetched data from the fetching thunk directly but I think this is not the solution ? Am I wrong ?
Or maybe this logic should go to the reducer ?
I know this must be simple stuff but I can't get over it, making me trying over-complicated things for, I guess, something as simple as this.
Any help would be greatly appreciated. Thank you very much
Our official Redux Toolkit package specifically has a createEntityAdapter API that implements managing data in a normalized form in the store.
For examples of how to use it, see the "Redux Essentials" core docs tutorial, Part 6: Performance and Normalizing Data, and the "Managing Normalized Data" section in the Redux Toolkit Usage Guide.

Redux-Toolkit: how to deal with an entity with compound keys?

I'm trying to use Redux-Toolkit's createEntityAdapter in an entity that has compound keys. For example, my territories entity has a type (municipality, state, biome, etc) and a geocode number. The pair {type, geocode} is the compound key of this entity.
I want to be able to use selectById and other selectors. My first thought was to create an id field that concatenates type, ";" and geocode, but I'm sure there's a better way.
import { createEntityAdapter } from '#reduxjs/toolkit'
const adapter = createEntityAdapter({
// selectId: (item) => ???,
})
const APIresponse = {
data: [
{ type: 'state', geocode: 1, value: 123},
{ type: 'state', geocode: 2, value: 66},
{ type: 'municipality', geocode: 1, value: 77},
{ type: 'municipality', geocode: 2, value: 88},
{ type: 'municipality', geocode: 3, value: 99}
]
}
I'm a Redux maintainer and the person who implemented createEntityAdapter for RTK.
createEntityAdapter does assume that you have some kind of unique ID field in your data. If you don't have a unique ID field from the original data, you've got three options I can think of:
Generate a unique ID for each item when you are processing the API response (but before any "loaded" action is dispatched)
Concatenate together some combination of fields to create a synthesized id field when you are processing the API response
Implement selectId so that it returns a combination of fields each time

Resources